标签:
refer :
http://blog.thoughtram.io/angular/2016/09/15/angular-2-final-is-out.html ( search Dependency Injection )
小说明 :
大致流程 : 把 providers 写入 injector, 然后通过 injector 来注入 service.
单列 : 一个 service 在一个 injector 里是单列.
查找逻辑 : injector 有父子关联, 如果子 injector 没有发现 provider 那么它会去父 injector 找, 和 js prototype 差不多概念.
component + DI : angular2 为每一个 component 创建了 injector, 然后它们有父子串联的关系.
4 种方式设置 providers
1. useClass
providers: [{ provide: AppService, useClass: AppService }]
providers: [AppService]
如果, provide 和 useClass 是同一个那么可以像第2个那样缩写哦.
2.useValue, 当 service 不是一个 class 对象, 就可以用这个, stringOrToken 之后讲.
@Component({ selector: ‘my-app‘, template: ‘<h1>My First Angular App</h1>‘, providers: [{ provide : "stringOrToken", useValue : "xxx" }] }) export class AppComponent { constructor( @Inject("stringOrToken") private service: string) {} ngOnInit() { console.clear(); console.log(this.service); //xxx } }
3. useExisting
用途 refer : http://blog.thoughtram.io/angular/2016/09/14/bypassing-providers-in-angular-2.html
@Component({ selector: ‘my-app‘, template: ‘<h1>My First Angular App</h1>‘, providers: [ { provide: "stringOrToken", useValue: "xxx" }, { provide: "otherString", useExisting: "stringOrToken" } ] }) export class AppComponent { constructor( @Inject("otherString") private service: string) {} ngOnInit() { console.clear(); console.log(this.service); //xxx } }
简单说就是让你用不同的 "名字" 调用同一个 service.
4. useFactory
@Component({ selector: ‘my-app‘, template: ‘<h1>My First Angular App</h1>‘, providers: [ AppService, { provide: "stringOrToken", useFactory: (appService) => { console.log(appService); return "zzz"; }, deps: [AppService] //这里只能是简单的 class 注入哦, 不是无限嵌套哦 } ] }) export class AppComponent { constructor( @Inject("stringOrToken") private service: string) {} ngOnInit() { console.clear(); console.log(this.service); //zzz } }
@inject() 和
标签:
原文地址:http://www.cnblogs.com/keatkeat/p/5902268.html