[Angular 2] Factory Provider

In this lesson, we discuss how and when to use factory providers, to enable dependencies that shouldn’t be available to Angular’s DI.

If you have this service:

export class LoggerProvider {
    constructor(enabled: boolean){
        if(enabled){
            console.log("Logger is enabled")
        }
    }
}

Which requires you provide param in constructor function. 

If you just use it like normal provider:

@Component({
   selector: 'todos',
   providers: [TodoService, LoggerProvider],
   template: `...`  
})

It will NOT work, because when init the LoggerProvider instance, we need to pass a boolean value as a param.

But you can use factory provider for this:

 providers: [
    TodoService
   ,{
        provide: LoggerProvider, useFactory: () => {
             return new LoggerProvider(true)
        }
    } 
],    
原文地址:https://www.cnblogs.com/Answer1215/p/5877014.html