DongBin Kim
DongBin Kim

Reputation: 1879

The clear meaning of the decorator @Injectable in Angular 5+

As far as I know, a class can get dependencies injected from the Angular injector with a decorator such as @Injectable, @Component.

So I consider @Injectable decorator as some sort of a "badge", telling Angular that "I(class) allow you to inject dependencies I request" and I believe this is correct.

But this sentence from the official document confuses me:

@Injectable()
export class UserContextService {}

The @Injectable decorator indicates that the Angular DI system is used to create one or more instances of UserContextService.

In my knowledge, @Injectable decorator has nothing to do with the injector creating an instance of the class.

Am I missing something?

P.S. The official document link for the sentence above

Upvotes: 3

Views: 1518

Answers (1)

Dean
Dean

Reputation: 2273

Interestingly enough, the documentation is wrong on this one. @Injectable actually means "I(service) can have other services injected into me". Consider this service called Service2 that attempts to have Service1 injected in the constructor:

// If you remove this, you will get an error
@Injectable()
export class Service2 {
  constructor(private service: Service1) { 

  }
}

As noted by the comment, removing @Injectable() causes this to throw an error. You can try it using a StackBlitz I created. Components don't need @Injectable() to have services injected in them though.

I found an issue where this was discussed but nothing seemed to ever come from it. To think, I took the documentation at face value and have been using @Injectable() incorrectly this entire time. Thank you for this question.

This prompted me to dig even deeper and look at the test referenced by the documents. It fails, but not for the reason the documentation says it fails. And they actually have a test to verify you can inject a service that does not have the decorator. I wrote up more information for the curious here.

Upvotes: 3

Related Questions