首页 > 代码库 > [Angular 2] 6. Factory Provider

[Angular 2] 6. 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)        }    } ],    

 

[Angular 2] 6. Factory Provider