在多个 boostrapped 组件之间共享服务

Share services between multiple boostrapped component

我创建了 2 个单独引导的组件(在 2 个不同的视图中),我尝试在这两个组件之间共享一个独特的服务(单例)。该服务用于操作这些组件之一。我的服务:

@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]);

还有我的第二个组件,它是从第一个组件中分离出来的:

export class TextboxAutocomplete {    
    constructor(private modelService: ModalContainerService) {}
}

但是 ModalContainerService 不再包含我的第一个组件的引用... 是否可以在单独引导的 2 个组件之间共享数据/服务?

我没有得到你想要分享的服务,所以我使用 FooService 作为名字。

在 Angular 之外创建 FooService 的实例,然后将值作为提供者传递给 booth bootstrap()

var fooService = new FooService();
bootstrap(AppComponent1, [provide(FooService, {useValue: fooService})]);
bootstrap(AppComponent2, [provide(FooService, {useValue: fooService})]);