如何使用特定的进样器在ng-bootstrap模式中打开组件?

时间:2017-03-03 00:09:17

标签: angular bootstrap-modal ng-bootstrap

我开始使用ng-bootstrap模式在弹出窗口中打开我的组件。我有许多组件,每个组件都需要您自己的注入器,因为每个组件都使用相同服务的不同实例。有没有办法像“ViewContainerRef”中那样传递组件和注入器:

let componentRef = viewContainerRef.createComponent(myComponentFactory, 0, 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},
            {provide: 'ServiceProvider', 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, 0, childInjector, []);

1 个答案:

答案 0 :(得分:0)

默认情况下它不起作用吗?

假设您有两个组件,每个组件声明相同的服务:

@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的不同实例,没有?