使用 ngx-bootstrap 将服务的特定实例传递给模式的正确方法



我正在尝试将服务的特定实例传递给ngx-bootstrap模式内部的组件。

但是,由于模态不是启动模态的组件的子级,因此如果我尝试注入它,它将无法解决服务依赖项。

我能够在打开模态时将服务作为数据传递,然后作为其子模态的输入,它可以工作,但这似乎不是正确的方法。

我不想使提供的服务在:"root"中或在模块中提供,因为它包含整个生命周期中的持久数据,组件提供它以及使用该数据的函数。

我考虑在打开模态时传递一个注入器,但似乎 ngx-bootstrap 不支持该选项。我发现传递自定义注入器的唯一示例是 ng-bootstrap。

如果我无法将注入器传递给模态,但我仍然希望能够将其注入基本模态组件的子组件,那么将服务作为数据传递给模态似乎没问题。

堆栈闪电战示例(将服务作为数据传递,然后作为输入传递(:

https://stackblitz.com/edit/ngx-modal-25zz6k?file=src/app/app.component.ts

主要成分:

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService],
})
export class AppComponent {
modalRef: BsModalRef;
constructor(private modalService: BsModalService, private appService: AppService, private injector: Injector) {}
openModal() {
this.appService.increment();
this.modalRef = this.modalService.show(SomeComponent,  {
initialState: {
title: 'Modal title',
appService: this.appService,
},
});
}
}

模态组件:

export class SomeComponent implements OnInit {
appService: AppService;
title;
constructor(
public modalRef: BsModalRef,
) {
}
ngOnInit() {
}
}

某个组件的子组件:

export class ChildComponent implements OnInit {
constructor(
public modalRef: BsModalRef,
) { }
@Input() appService: AppService;
count: number = 0;
ngOnInit() {
this.count = this.appService.num;
}
}

理想情况下,我希望它以类似于 ng-bootstrap 的方式工作,我可以将自定义注入器传递给类似于以下内容的模态:

this.modal.open(SomeComponent, {
injector: Injector.create([{
provide: AppService, useValue: this.appService
}], this.injector)
}) 

能够将AppService添加到SomeComponent的注入器中也可以,但是从我尝试的唯一注入方法来看,注入它的唯一方法是在构造组件时执行它,并且在ngOnNit在SomeComponent中运行之前不会定义AppService。

我觉得这样的东西在某个组件中也可以工作:

constructor(@Inject(forwardRef(() => returnObservableForAppService)) appServiceObsv: Observable<AppService>) { }

但是注入可观察量而不是实际服务似乎与仅将其作为输入传递大致相同。

如何使用Injector创建服务的实例,您可以将其导入到所需的组件中:

const injector = Injector.create({
providers: [
{ provide: AppService, deps: [] },
]
});
export const appService = injector.get(AppService);

然后在所需的组件中,导入appService并使用它:

import { appService } from '....';
// ...
openModal() {
appService.increment();
this.modalRef = this.modalService.show(SomeComponent, {
initialState: {
title: 'Modal title'
},
});
}

导入相同的ChildComponent和...

ngOnInit() {
this.count = appService.num;
}

您的分叉堆栈闪电战

最新更新