一、注入器(从容器中获取对象,相当于java中的@Autowired)(在组件的xxx.component.ts中使用)
constructor(private productService: ProductService){...}
二、提供器(把对象放入容器,相当于java中的@Component)(在app.module.ts -> @NgModule -> providers属性中配置),四种方式示例:
providers:[ProductService]
providers:[{provide:ProductService,userClass:ProductService}]
providers:[{provide:ProductService,useClass:AnotherProductService}]
providers:[{provide:ProductService,useFactory:() => {...}}]
三、创建一个di项目,用于angular依赖注入测试demo
ng new di --routing
四、新建一个组件 product1
ng g component product1
五、新建一个服务,在多个组件之间共享 product,放在shared文件夹下
ng g service shared/product
六、在product.service.ts中声明一个Product对象和一个getProduct()函数
import { Injectable } from '@angular/core';
@Injectable()
export class ProductService {
constructor() { }
getProduct(): Product {
return new Product(0, 'iphone7', 5899, '最新款');
}
}
export class Product {
constructor(public id: number,
public title: string,
public price: number,
public desc: string){
}
}
七、在app.module.ts中的providers属性放入ProductService
providers: [ProductService]
八、修改product1.component.ts从容器中获取对象
import { Component, OnInit } from '@angular/core';
import {Product, ProductService} from '../shared/product.service';
@Component({
selector: 'app-product1',
templateUrl: './product1.component.html',
styleUrls: ['./product1.component.css']
})
export class Product1Component implements OnInit {
// 声明一个属性获取对象
product: Product;
// 从容器中注入对象
constructor(private productService: ProductService) { }
ngOnInit() {
this.product = this.productService.getProduct();
}
}
九、product1.component.html
<div>
<h4>商品详情</h4>
<h6>名称:{{product.title}}</h6>
<h6>价格:{{product.price}}</h6>
<h6>描述:{{product.desc}}</h6>
</div>
十、修改主模板app.component.html
<div>
<div>
<h3>基本的依赖注入样例</h3>
</div>
<div>
<app-product1></app-product1>
</div>
</div>
<router-outlet></router-outlet>
十一、启动项目,访问localhost:4200
十二、使用工厂和值声明提供器(根据条件new不同的对象)
providers: [{
provide: ProductService,
useFactory: (logger:LoggerService, appConfig) => {
if (appConfig.isDev) {
return new ProductService(logger);
}else {
return new AnotherProductService(logger);
}
},
deps: [LoggerService, 'IS_DEV_ENV']
},
LoggerService,
{provide: 'APP_CONFIG', userValue: {isDev: false}}]