Angular 2 @Injectable () - how it works

I am trying to understand the need to add @Injectable() decorations in services in angular 2.

From the documentation: https://angular.io/docs/ts/latest/guide/dependency-injection.html

Why don't we add @Injectable () to HeroesComponent? We can add it if we want. This is not necessary because HeroesComponent is already decorated with @Component. TypeScript creates metadata for any class with a decorator, and any decorator will do.

Basically you need to add @Injectable() if there is no other decoration, because if there is any type of decoration, the TypeScript compiler will automatically generate dependency information based on the variables that you passed in the constructor, for example: constructor(private logger: Logger)

Is it correct? Thanks

+6
source share
1 answer

I think this is a little strange, and I really don't understand why they are telling you to add it for best practice. If you add it to each class, this is the best practice, I do not understand why this is necessary at all. It would be easier if the infrastructure checked each class, if the designer needs injected materials or not. This could be resolved using the typescript command line property to always generate (mock) metadata.

Advice to always add it, I think it seems that the compiler always adds metadata (which is impossible, as far as I know). You can also (with vigilance) only (and always) add it to classes that need injected material, even if they have a different decorator. That would probably be the most obvious decision - but hey - being sloppy can be both a bad and a good thing. In this case, you will be the judge.

TL DR If you do not have other decorators AND , if your constructor needs / etc services , then you need it.

+7
source

All Articles