我开始使用ng-bootstrap模式在弹出窗口中打开我的组件.我有许多组件,每个组件都需要您自己的注入器,因为每个组件都使用相同服务的不同实例.有没有办法像“ViewContainerRef”中那样传递组件和注入器:
let componentRef = viewContainerRef.createComponent(myComponentFactory,myInjector,[]);
我需要这样的东西:
NgbModal.open(MyComponet,myInjector);
谢谢.
编辑添加更多细节.
我需要注入的服务和对象是在运行时确定的,如下所示:
// Services @Injectable() export class MyService1 { constructor( @Inject('ServiceProvider') private _serviceProvider: any ) { } } @Injectable() export class MyService2 { constructor( @Inject('ServiceProvider') private _serviceProvider: any ) { } } // Components @Component({ ... }) export class CompA { constructor( @Inject('MyService') private _service: MyService1 | MyService2,@Inject('MyParentService') private _parentService: MyService1 | MyService2 ) { } } @Component({ ... }) export class CompB { constructor( @Inject('MyService') private _service: MyService1 | MyService2,@Inject('MyParentService') private _parentService: MyService1 | MyService2 ) { } }
因此,当用户请求操作时,我需要提供正确的服务(对于组件)和正确的“ServiceProvider”(对于服务).这是父母发生的事情:
switch (action) { case 'one': providers = [ {provide: 'MyService',useClass: MyService1},{provide: 'ServiceProvider',useValue: this._objectsA} ]; break; case 'two': providers = [ {provide: 'MyService',useClass: MyService2},useValue: this._objectsB} ]; break; } providers = providers.concat([ {provide: 'MyParentService',useValue: this._service} ]); switch (context) { case 'add': component = compA; break; case 'edit': component = compB; break; } let resolvedProviders = ReflectiveInjector.resolve(providers),childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders,this._injector); // It was good if I'm able to resolve the component dynamically let factory = this._componentFactoryResolver.resolveComponentFactory(component); // And finally open my popup this._ngbModal.open(factory,childInjector); // Like when we use the viewContainerRef // let componentRef = viewContainerRef.createComponent(factory,childInjector,[]);
解决方法
它默认不起作用吗?
假设您有两个组件,每个组件声明相同的服务:
@Component({ providers: [MyService] }) export class CompA { constructor(private service: MyService) { } } @Component({ providers: [MyService] }) export class CompB { constructor(private service: MyService) { } }
然后,当您通过模态服务实例化这些组件时:
NgbModal.open(CompA); NgbModal.open(CompB);
他们每个人都得到一个不同的MyService实例,不是吗?