The common misconception of @Injectable() in angular

Nick Raphael - Dec 11 '19 - - Dev Community

The official angular docs give the following description of @Injectable()...

https://angular.io/api/core/Injectable
"Decorator that marks a class as available to be provided and injected as a dependency."

I think that description isn't right. Or at least it leads me to misinterpret the meaning. Let me start by defining a concrete example...

Let's say we have AppComponent and UserService. By default the angularCli will add @Injectable() to the service when it is generated.

Now, to me, the official statement makes me think that @Injectable() on UserService allows us to add it in the constructor of AppComponent as a dependency. "...marks a class as available to be provided and injected as a dependency". But what happens if we remove the @Injectable() from the service? Let me tell you - it still gets injected into AppComponent.

Now lets add a second service, OrderService and add it as a dependency of UserService. Now our application throws an error. "Can't resolve all parameters for UserService"

When we add @Injectable() to the UserService it actually allows UserService to have dependencies injected into itself. Not allow itself to be injected into AppComponent.

So we add @Injectable() to UserService since it needs to register with the dependency injected system to get a reference to OrderService. We can even remove @Injectable() from OrderService since it doesn't have any dependencies.

I'm not saying you should remove @Injectable(). In fact, you should leave it there even if your service doesn't have dependencies. It does no harm. I once had a service where the injected services weren't working and it took me ages to notice that @Injectable() was missing. So don't do that.

You might wonder why components are not marked with @Injectable() since they have dependencies injected into them. Well, if memory serves, any decorator will have the effect of registering the class with the DI system. So in this case @Component() is doing it.

Am I the only one who feels the description of @Injectable() isn't quite right? Let me know.

. . . . . . . . . . . . . . . . . . . . . . . . . .