3

我创建了 2 个单独的组件(在 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 个组件之间共享数据/服务?

4

1 回答 1

4

我没有得到您想要分享的服务,因此我使用FooService它作为名称。

创建一个FooService外部 Angular 的实例,然后将值作为提供者传递给展位bootstrap()

var fooService = new FooService();
bootstrap(AppComponent1, [provide(FooService, {useValue: fooService})]);
bootstrap(AppComponent2, [provide(FooService, {useValue: fooService})]);
于 2016-02-24T16:45:16.337 回答