码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular 2] 6. Factory Provider

时间:2016-09-16 21:08:41      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5877014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!