如何订阅通过@ angular / cdk / portal注入的Observable of Component?

前端之家收集整理的这篇文章主要介绍了如何订阅通过@ angular / cdk / portal注入的Observable of Component?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试实现一个基本的(非常基本的)模态实现.我有一个ModalService和一个ModalComponent.

ModalService创建ModalComponent的一个实例,并使用@ angular / cdk / portal将其注入页面.

我可以得到模态显示就好了:-)

ModalComponent有一个Observable属性,我希望ModalService能够订阅,这样当在模态中单击“关闭”按钮时,可以发出一个值,ModalService可以关闭模​​态.

但是,当组件发出值时,服务不会对其执行操作.在服务方面,它看起来像我订阅,但从组件方面,它显示0观察员.

我想也许我可以使用一个典型的@Output()EventEmitter,但我不确定是否因为在modal类中挂起它,因为child元素最初不存在.

我想也许我的组件引用不太正确(也许我有两个不同的?).我正在尝试this answer的建议

我有什么想法我做错了吗?

服务

export class ModalService {

    private modalPortal: ComponentPortal<any>;
    private bodyPortalHost: DomPortalHost;

    constructor(private componentFactoryResolver: ComponentFactoryResolver,private appRef: ApplicationRef,private injector: Injector) {
    }

    showModal(modalName: string) {

        // set up the portal and portal host
        this.modalPortal = new ComponentPortal(ModalComponent);
        this.bodyPortalHost = new DomPortalHost(
            document.body,this.componentFactoryResolver,this.appRef,this.injector);

        // display the component in the page
        let componentRef = this.bodyPortalHost.attach(this.modalPortal);


        // listen for modal's close event
        componentRef.instance.onModalClose().subscribe(() => {
            console.log('I will be very happy if this this gets called,but it never ever does');
            this.closeModal();
        });

        // console.log(componentRef.instance.onModalClose()) shows 1 subscriber.
    }

    closeModal() {
        this.bodyPortalHost.detach();
    }
}

零件

export class ModalComponent {

    private modalClose: Subject<any> = new Subject();

    onModalClose(): Observable<any> {
        return this.modalClose.asObservable();
    }

    closeModal() {
        // console.log(this.onModalClose()) **shows zero observers**   :-(
        this.modalClose.next();
        this.modalClose.complete();
    }
}

此外,如果我碰巧提出错误的问题,意味着有更好的整体方法,我愿意接受建议.

猜你在找的Angularjs相关文章