Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Angular 2 factory functions?

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?

like image 996
johncol Avatar asked Aug 06 '16 18:08

johncol


People also ask

What is difference between service and factory in Angular?

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.

What is the use of useClass in Angular?

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.

Which uses this is it service or factory?

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 .

What is useFactory Angular?

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.


1 Answers

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.

like image 172
Günter Zöchbauer Avatar answered Oct 25 '22 11:10

Günter Zöchbauer