2017-08-30 20 views
1

喷油器一类的新实例我有两个注射类在我的角度应用我怎样才能使用的,而不是单件

@Injectable() 
class B {} 

@Injectable() 
class A { 
    constructor(b:B) { } 
} 

我想A类是单身和B类是瞬态

我开始知道我可以在类A中使用ReflectiveInjector.resolveAndCreate来获得类B的实例。有什么更好的实现方法?

+0

另请参见https://stackoverflow.com/questions/38472103/create-new-instance-of-class-that-has-dependencies-not-understanding-factory-pr/38473200#38473200和https:// stackoverflow .com/questions/38482357/angular2-how-to-use-multiple-instances-of-same-service/38483406#38483406 –

回答

2

由于对供应商的所有现有配方创建单身,甚至是工厂,你可以创建自己的喷油器,继承组件喷油器的所有供应商,并使用resolveAndInstantiate方法每次都得到新的实例:

import { Component, Inject, Injector, ReflectiveInjector } from '@angular/core'; 

class P { 
} 

const ps = []; 

class C { 
    constructor(@Inject(P) p) { 
    ps.push(p); 
    } 
} 

@Component({ 
    moduleId: module.id, 
    selector: 'my-app', 
    templateUrl: 'app.component.html', 
    styleUrls: ['app.component.css'] 
}) 
export class AppComponent { 
    name = 'Angular'; 

    constructor(injector: Injector) { 
    const parent = ReflectiveInjector.resolveAndCreate([P], injector); 
    const child = parent.resolveAndCreateChild([C]); 
    const c1 = child.resolveAndInstantiate(C); 
    const c2 = child.resolveAndInstantiate(C); 
    console.log(c1 === c2); // false 

    console.log(ps[0] === ps[1]); // true 

    } 
} 

Here is the demo

另请注意,ReflectiveInjector已在@ 5.x.x中弃用。而且似乎在新的StaticInjector中没有其他选择。关于这个我报告了an issue

+0

感谢您的回答。我有一个问题,但我们不能使用常规的工厂方法,它需要时返回所需的对象的新实例?其次是不ReflectiveInjector弃用?你是否仍然推荐使用它 – SRK

+0

@SRK,不,工厂不会每次都返回新的实例,无论它在第一次缓存它时返回什么。所以,即使你在内部返回新的AClass(),你仍然会得到一个单例 –

+0

@ SRK,同时请记住ReflectiveInjector已被弃用。而且,新的StaticInjector似乎没有其他选择。我[报告了一个问题](https://github.com/angular/angular/issues/18946)。你可以阅读更多关于StaticInjector [这里](https://blog.angularindepth.com/angular-introduces-staticinjector-should-you-care-4e059eca030c) –