Angular (2+): What does the @Injectable() decorator do?
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:
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!

Look at that interface.. It's blank! 😕
So why do we need it? The Angular documentation says this:
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.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 theemitDecoratorMetadata
compiler option is true (as it should be in thetsconfig.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.
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!
Useful post.
ReplyDeleteAngularjs Training in Chennai
ReplyDeleteReally awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.
Hire Offshore Angularjs 2 Developer in India