0

I'm trying to figure out the difference between two ways of service injection in Angular 5:

1

constructor(private _anyService: AnyService) { }

2

private _anyService: AnyService;
constructor(private _injector: Injector) {
  this._anyService = this._injector.get(AnyService);
}

Do we finally get the same result, will this._anyService behave the same in both cases?

P.S.: The context is not important for this example, the question is only about the service instances, doesn't matter, which variables/class properties hold this instance.

Commercial Suicide
  • 14,875
  • 14
  • 62
  • 80
  • I think the first one is a short-hand syntax of the second. Not sure though. – SiddAjmera Aug 31 '18 at 14:04
  • The difference that I see is that, in the first case, `_anyService` can be used everywhere and at any time in the class, while in the second case, `anyService` is available only inside of `_anyMethod`. And if you declare `anyService` as a class member in the second case, then you would have to check if it has been defined before using it in another method of the class. – ConnorsFan Aug 31 '18 at 14:05
  • @SiddharthAjmera, but why if we will try to inject service inside another one service via constructor, it will throw an error? – Commercial Suicide Aug 31 '18 at 14:06
  • @CommercialSuicide, it shouldn't ideally. A scenario when it might, is when both the services are not decorated with the `@Injectable()` decorator. Is that the case? If not, what is the error that you're getting? – SiddAjmera Aug 31 '18 at 14:08
  • @CommercialSuicide - The error may be caused by [circular dependency](https://stackoverflow.com/q/36378751/1009922). – ConnorsFan Aug 31 '18 at 14:10
  • @ConnorsFan, yes, I mean is there any difference between got instances of this `anyService`? The context is not important, it's just an example, it doesn't matter, will we store it class property or `const` variable, the question is not really about that. – Commercial Suicide Aug 31 '18 at 14:10
  • The advantages of the first one is mocking your service for unit testing, and the service is available when the instance is created, whereas your second one you would have to call that `_anyMethod()` before it is available. – penleychan Aug 31 '18 at 14:11
  • @SiddharthAjmera, yes, let's imagine, that all services are decorated with `@Injectable()`. The error is about the circular dependency. But if i do with `this._injector.get(AnyService)` - there are no errors – Commercial Suicide Aug 31 '18 at 14:11
  • But what about providing this service as a singleton? The way we're injecting it is not important, right? – Commercial Suicide Aug 31 '18 at 14:14
  • I've updated the question, hope it became more clear. – Commercial Suicide Aug 31 '18 at 14:23

0 Answers0