且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用同一服务的多个实例

更新时间:2023-11-22 16:52:58

Angular DI为每个提供程序维护一个实例.如果您有两个具有相同类型的构造函数参数,它们将解析为相同的实例.

Angular DI maintains a single instance per provider. In your case if you have two constructor parameters with the same type, they resolve to the same instance.

您可以做的是提供一个工厂功能(尽管它也使用了一个简单的useFactory提供程序事件,但它也使用了该功能)

What you can do is to provide a factory function (different from a simple useFactory provider event though it uses it as well)

(示例摘自 https://***.com/a/37517575/217408 )

{ provide: EditorService, useFactory: 
    (dep1, dep2) => {
        return (x) => { 
            new EditorService(x, dep1, dep2);
        }
    }, deps: [Dep1, Dep2]
})

....

constructor(@Inject(EditorService) editorServiceFactory: any) {
  let editorService1 = editorServiceFactory(1);
  let editorService2 = editorServiceFactory(2);
}

如果您有固定数量的实例,则该方法可以正常工作:

If you have a fixed number of instances this should work:

{ provide: 'instance1', useClass: EditorService },
{ provide: 'instance2', useClass: EditorService },

export class SomeComponent {
    constructor(
        @Inject('instance1') private _appleEditorService: EditorService,
        @Inject('instance2') private _pearEditorService: EditorService) {}
}