1. 程式人生 > >Angular學習筆記3--依賴注入

Angular學習筆記3--依賴注入

基本用法

1.建立服務
ng g service product/product
2.編寫服務

getProduct(): Product {
  return new Product('123', 'productName')
}
getProduct(): Product {
    return new Product('123', 'productName')
  }

3.新增配置

@NgModule({
  providers: [ProductService]
})

4.使用

private productId: string;
private productName: string;
constructor(private productService: ProductService) {
}
ngOnInit() {
  this.productId = this.productService.getProduct().id;
  this.productName = this.productService.getProduct().name;
}

基於原有服務提供的服務

1.建立服務
2.編寫服務

export class AnotherProductService implements ProductService{
  getProduct(): Product {
    return new Product("aaaaa", "another-product");
  }
}

3.在component中新增配置

@Component({
  providers: [{provide: ProductService, useClass: AnotherProductService}]
})

4.使用

private productId: string;
private productName: string;
constructor(private productService: AnotherProductService) { 
ngOnInit() {
  this.productId = this.productService.getProduct().id;
  this.productName = this.productService.getProduct().name;
}

工廠函式提供器

providers: [{
    provide: ProductService,
    useeFactory: (logger: LoggerService, appConfig) => {
      if (appConfig.isDev) {
        return new ProductService(logger);
      } else {
        return new AnotherProductComponent(logger);
      }
    },
    deps: [LoggerService, "APP_CONFIG"]
  }, LoggerService, 
  {
    provide: "APP_CONFIG", useValue: {isDev: false}
  }]