在多个 boostrapped 组件之间共享服务 [英] Share services between multiple boostrapped component

查看:24
本文介绍了在多个 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]);

还有我的第二个组件,它与第一个组件分离:

And my second component, which is boostrapped apart of the first component :

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

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

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.

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

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 组件之间共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆