问题描述
我创建了单独boostrapped(在2个不同的看法)2组件,我尝试分享这些2组件之间的独特的服务(单身)。该服务是利用操纵这些部件中的一个。我的服务:
I created 2 components which are boostrapped separately (in 2 different views), and I try to share a unique service (singleton) between these 2 components. The service is use to manipulate one of these component. My service :
@Injectable()
export class ModalContainerService {
private component: ModalContainer;
constructor() {}
setComponent(component: ModalContainer) {
this.component = component; <-- for holding the reference to my component
}
showFirst() {
this.component.showFirst();
}
addModal(modal: Type) {
this.component.addModal(modal);
}
}
第一部分:
export class ModalContainer {
private modals: Array<ComponentRef> = [];
constructor(
private loader: DynamicComponentLoader,
private element: ElementRef,
private modalService: ModalContainerService) {
modalService.setComponent(this); <-- where I set the component reference for my service
}
showFirst(): void {
this.modals[0].instance.show();
}
addModal(modal: Type) {
this.loader
.loadIntoLocation(modal, this.element, 'modalContainer')
.then((ref) => {
this.modals.push(ref);
});
}
}
bootstrap(ModalContainer, [ModalContainerService]);
和我的第二成分,该boostrapped第一组分隔开
And my second component, which is boostrapped apart of the first component :
export class TextboxAutocomplete {
constructor(private modelService: ModalContainerService) {}
}
但ModalContainerService不包含我的第一个组件的参考了...
是否有可能分享DATAS / 2组件之间的服务分开boostrapped?
But the ModalContainerService doesn't contains the reference of my first component anymore ...Is it possible to share datas / services between 2 components boostrapped separately ?
推荐答案
我没有得到你想要所以我用 FooService接口
姓名,分享什么样的服务。
I didn't get what service you want to share therefore I use FooService
as name.
创建 FooService接口
的一个实例外角然后传递价值提供商展台引导()
Create an instance of FooService
outside Angular then pass the value as provider to booth bootstrap()
var fooService = new FooService();
bootstrap(AppComponent1, [provide(FooService, {useValue: fooService})]);
bootstrap(AppComponent2, [provide(FooService, {useValue: fooService})]);
这篇关于多个boostrapped组件之间共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!