Search code examples
angulardependency-injectioninjectable

What does an empty @Injectable() decorator actually mean in Angular?


I'm not regular with Angular development. One thing I learnt about the @Injectable() decorator is that it means -

  • this class can have/take injected dependencies

and not

  • this class can be injected as a dependency

I cannot refer to any specific source right away (bad memory, getting old), but it was from articles online and may be some tutorials. I'm talking about an empty @Injectable() by the way, not about one with the providedIn property.

Anyway, looks like the Angular docs' narrative is aligned to reflect the later meaning. Here it says that the purpose of the decorator is

  • to show that the class can be injected.

and also here that -

  • The @Injectable() decorator specifies that Angular can use this class in the DI system.

So:

  1. What exactly does an empty @Injectable() decorator actually indicate?
  2. If the meaning of the @Injectable() is "this class can be injected as a dependency", then how come I can use a service class without the @Injectable() decorator as a dependency and it still works fine?

Solution

  • technically empty @Injectable() decorator marks the class to be processed with angular compiler. it analyzes parameters in the constructor and creates correct factory for that. for example class:

    // no @Injectable()
    class MyService {
      constructor(http: HttpClient) {}
    }
    

    can not be provided in providers array in a simple way providers: [MyService], as angular doesn't know what to provide in the constructor.

    apart from constructor injection, it doesn't really do anything. Ir just tells developers that this class should be used in DI