一、注入器(從容器中獲取對象,相當於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}}]