前言
上一篇博客介绍了注入器和提供器,同时也简单的讲解了一下控制反转,这篇博客是使用了工厂方法来定义提供器,所以可以过来了解一下。
内容
这个例子是在提供器方法的例子上建立的:
1.首先删除product2.component.ts
中的代码:
providers:[{
provide:ProductService,useClass:AnotherProductService
}]
最终效果:
import{Component,OnInit}from'@angular/core';
import{Product,ProductService}from'../shared/product.service';
import{AnotherProductService}from'../shared/another-product.service';
@Component({
selector:'app-product2',
templateUrl:'./product2.component.html',
styleUrls:['./product2.component.css']
})
exportclassProduct2ComponentimplementsOnInit{
product:Product;
constructor(privateproductService:ProductService){}
ngOnInit(){
this.product=this.productService.getProduct();
}
}
2.在app下的module中修改providers中的内容:
providers:[{
provide:ProductService,
useFactory:()=>{
constlogger=newLoggerService();
constdev=Math.random()&