6

I can't imagine a situation where I need to use a factory provider.

According to the offical docs https://angular.io/docs/ts/latest/guide/dependency-injection.html the situation is that one may not be able to access a service (service-b) from within another service (service-a), but, the factory function does (have access to service-b). So, when would something like this really happen?

johncol
  • 584
  • 1
  • 7
  • 13
  • Where can I find the text you mention in the linked doc? "one may not be able to access a service (service-b) from within another service (service-a), but, the factory function does" – Günter Zöchbauer Aug 06 '16 at 18:53
  • That was my interpretation of the docs, look for it in https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#injector-providers under the section "Factory providers" just before the text "Why? We don't know either. Stuff like this happens." – johncol Aug 07 '16 at 20:32

1 Answers1

7

You can register for a provider by just passing the class

providers: [MyService]

This only works if Angulars DI can instantiate MyService.

If you have for example

@Injectable()
class MyService {
  constructor(private http: Http, private String configVal) {}
}

then DI is not able to create an instance because String is not a valid key for a provider (primitive types don't work as provider key.

If you need this you can use a factory function like

providers: [
    {
      provide: MyService, 
      useFactory: (http) => {
        return new MyService(http, 'http://mydbserver.com:12345');
      },
      deps: [Http]
    }
]

This way you fully control how a new instance is created and Angulars DI only needs to know that it needs to call the factory function with an instance of Http.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I get that, but, e.g. one can easily create a service, MyConfigService, which gives you those config values and inject it into MyService. So I still wonder if there is actually another reason for the angular framework to allow us define providers this way.. Anyway thanks for your answer! – johncol Aug 07 '16 at 20:39
  • 2
    For example if you want to inject classes that don't have the `Injectable()` decorator and you can't add it because you don't own the source. I'm sure there are several others. – Günter Zöchbauer Aug 08 '16 at 05:36