Angular 如何使用Injector而不是singleton获取类的新实例

Angular 如何使用Injector而不是singleton获取类的新实例,angular,dependency-injection,Angular,Dependency Injection,在我的angular应用程序中有两个可注入类 @Injectable() class B {} @Injectable() class A { constructor(b:B) { } } 我希望A类是单态的,B类是瞬态的 我开始知道我可以在类A中使用ReflectiveInjector.resolveAndCreate来获得类B的实例。有没有更好的方法来实现这一点 由于提供程序的所有现有配方都创建了单例,甚至是工厂,所以您可以创建自己的注入器,从component injector继承

在我的angular应用程序中有两个可注入类

@Injectable()
class B {}

@Injectable()
class A {
  constructor(b:B) { }
}
我希望A类是单态的,B类是瞬态的


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

由于提供程序的所有现有配方都创建了单例,甚至是工厂,所以您可以创建自己的注入器,从component injector继承所有提供程序,并使用方法每次获取新实例:

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

  }
}


还要记住,
ReflectiveInjector
在@5.x.x中被弃用。在新的世界里似乎没有其他选择。我对此进行了报道。

有一种方法可以使用StaticInjector和函数式Javascript解决这个问题。使用Max Koretskyi answer,稍作修改,我得出以下结论:

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

class P {
}

const ps = [];

function pFactory() {
  return () => new P();
}

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

  constructor(@Inject(pFactory) pf) {
    let fn = pf.get(pFactory)
    ps.push(fn());
    ps.push(fn());
    console.log(ps[0] === ps[1]); // false
  }
}

谢谢你的回答,格言。但我有一个问题,我们不能使用常规的工厂方法,在需要时返回所需对象的新实例吗?第二,ReflectionVenjector不是不推荐吗?你还推荐使用吗it@SRK,不,工厂不会每次都返回新实例,无论它在第一次缓存时返回什么。因此,即使您在内部执行
返回新的AClass()
,您仍然会得到一个singleton@SRK另外,请记住ReflectVenjector已被弃用。而且似乎在新的静态注入器中没有替代品。我很担心。您可以阅读更多关于您的信息,谢谢。直到现在,我一直认为工厂每次调用它时都会返回一个新实例