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);
}
}
The first component :
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]);
And my second component, which is boostrapped apart of the first component :
export class TextboxAutocomplete {
constructor(private modelService: ModalContainerService) {}
}
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 ?
I didn't get what service you want to share therefore I use FooService as name.
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})]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With