angular--依赖注入
2017-12-30 本文已影响0人
林ze宏
在share目录下创建product服务:ng g service share/product
angular的依赖注入,只能通过构造函数的方式注入。
应用模块中注入服务:
app.module.ts:
import { LoggerService } from './share/logger.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ProductComponent } from './product/product.component';
import { HomeComponent } from './home/home.component';
import { Code404Component } from './code404/code404.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';
import { SellInfoComponent } from './sell-info/sell-info.component';
import { ChatComponent } from './chat/chat.component';
import { Product1Component } from './product1/product1.component';
import { ProductService } from './share/product.service';
import { Product2Component } from './product2/product2.component';
import { AnotherProductService } from './share/another-product.service';
@NgModule({
declarations: [
AppComponent,
ProductComponent,
HomeComponent,
Code404Component,
ProductDetailComponent,
SellInfoComponent,
ChatComponent,
Product1Component,
Product2Component
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [
LoggerService,
{
provide: 'IS_DEV_ENV', useValue: false // 常量
},
{
provide: 'IS_DEV_Obj', useValue: {isDev: true} // 对象
},
{provide: ProductService,
useFactory: (logger: LoggerService, isDev, isObj) => {
// const logger = new LoggerService();
// const dev = Math.random() > 0.5;
if (isObj.isDev) {
return new ProductService(logger);
}else {
return new AnotherProductService(logger);
}
},
deps: [LoggerService, 'IS_DEV_ENV', 'IS_DEV_Obj'] // deps表示ProductService需要依赖的其他服务(可以是变量、或者对象)
}
],
// providers: [ProductService, LoggerService],
bootstrap: [AppComponent]
})
export class AppModule { }
如果在组件中创建和应用模块中,相同的服务,会使用组件中的自己创建的服务
import { Component, OnInit } from '@angular/core';
import { Product, ProductService } from '../share/product.service';
import { AnotherProductService } from '../share/another-product.service';
@Component({
selector: 'app-product2',
templateUrl: './product2.component.html',
styleUrls: ['./product2.component.css']
providers: [{
provide: ProductService, useClass: AnotherProductService
}]
})
export class Product2Component implements OnInit {
private product: Product;
constructor(private productService: ProductService) { }
ngOnInit() {
this.product = this.productService.getProduct();
}
}