Angular (2+): What does the @Injectable() decorator do?

2334900180335494059
If you've looked at the description in your editor for the @Injectable() decorator, you'll see something like this:



Look at that interface.. It's blank! 😕

So why do we need it? The Angular documentation says this:
At runtime, injectors can read class metadata in the transpiled JavaScript code and use the constructor parameter type information to determine what things to inject.
Not every JavaScript class has metadata. The TypeScript compiler discards metadata by default. If the emitDecoratorMetadata compiler option is true (as it should be in the tsconfig.json), the compiler adds the metadata to the generated JavaScript for every class with at least one decorator.
While any decorator will trigger this effect, mark the service class with the @Injectable() decorator to make the intent clear.
Read the last sentence again: "...any decorator will [work]...". You can actually make your own decorator and use that instead of the @Injectable() decorator and your services will work. So it's actually just a quirk with Typescript and Angular's injectors needing a decorator to handle dependency injection correctly.

Recently, I attended an Angular workshop led by Google Developer Expert Nir Kaufman where he revealed this enlightening fact. So props to him for showing me this!

Comments

Post a Comment

Popular posts from this blog

Angular (2+): Core vs Shared Modules

Home Improvement: How to Make Your Toilet Flush Stronger.. Without Opening Toilet Tank

Food: How Carrot-Coconut Sunny-Side-Up Egg is Made