详解Angular依赖注入(2)

{ provide: Address, useFactory: ()=>{ return ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } } },

二、利用父子Injector。

constructor(private oc: OverlayContainer) { //接收一个provider数组 const injector = ReflectiveInjector.resolveAndCreate([ Person, { provide: Address, useFactory: ()=>{ if(environment.production){ return new Address("北京", "背景", "朝阳区", "xx街道xx号"); }else{ return new Address("西藏", "拉萨", "xx区", "xx街道xx号"); } } }, { provide: Id, useFactory:()=>{ return Id.getInstance('idcard'); } } ]); const childInjector = injector.resolveAndCreateChild([Person]); const person = injector.get(Person); console.log(JSON.stringify(person)); const personFromChild = childInjector.get(Person); console.log(person===personFromChild); //false }

子注入器当中没有找到依赖的时候会去父注入器中找

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zygzgd.html