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?
The major difference between an AngularJS service and an AngularJS factory is that a service is a constructor function and a factory is not. That is why, in the case of a factory, we return an object literal instead of using this.
useClass - this option tells Angular DI to instantiate a provided class when a dependency is injected. useExisting - allows you to alias a token and reference any existing one. useFactory - allows you to define a function that constructs a dependency.
service() is just a Constructor, it's called with new , whereas . factory() is just a function that returns a value. Using . factory() gives us much more power and flexibility, whereas a .
The useFactory field tells Angular that the provider is a factory function whose implementation is heroServiceFactory . The deps property is an array of provider tokens. The Logger and UserService classes serve as tokens for their own class providers.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With