如何订阅通过@ 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();
    }
}

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

谢谢!

最佳答案 这段代码对我来说只有很少的变化,所以我很困惑你的问题是什么.首先,我使用ng new使用Angular CLI创建了一个项目.然后我使用
instructions on their site安装了材料.

我创建了一个与你的相同的模态服务:

    import {ApplicationRef, ComponentFactoryResolver, Injectable, Injector} from '@angular/core';
import {DomPortalHost, ComponentPortal} from "@angular/cdk/portal";
import {ModalComponent} from "./modal/modal.component";

@Injectable({
  providedIn: 'root'
})
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();
  }
}

我创建了一个模态组件. TypeScript与您的相同:

import { Component, OnInit } from '@angular/core';
import {Observable, Subject} from "rxjs/index";

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  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();
  }

}

你没有给我们一个HTML模型,但这是我用过的:

<p>
  modal works!
</p>
<button (click)="closeModal()">Close Modal</button>

这是我的app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import { AppComponent } from './app.component';
import {ModalService} from "src/app/modal.service";
import { ModalComponent } from './modal/modal.component';

@NgModule({
  declarations: [
    AppComponent,
    ModalComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [ModalService],
  bootstrap: [AppComponent],
  entryComponents: [ModalComponent]
})
export class AppModule { }

注意我在entryComponents中定义了ModalComponent,并将ModalService定义为提供者.

app.component HTML:

<button (click)="showModal()">Show Modal</button>

和app.component打字稿:

import { Component } from '@angular/core';
import {ModalService} from "./modal.service";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  constructor(public modalService: ModalService){}

  showModal(){
       this.modalService.showModal("This is the modal name");
  }

}

我将ModalService注入构造函数并调用showModal方法以响应主应用程序中的按钮单击.

加载应用:
《如何订阅通过@ angular / cdk / portal注入的Observable of Component?》

单击按钮,模式显示出来.它看起来不像模态,但可能是因为缺少样式:

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

现在单击模态内的关闭按钮:

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

您看到模态已消失,控制台输出显示您的消息.

这篇文章是否有助于您找到错过的花絮?

有一点需要补充.如果要将模态中的数据发送到调用它的组件,请更改modalComponent的closeModal方法:

  closeModal() {
    // console.log(this.onModalClose()) **shows zero observers**   :-(
    this.modalClose.next('Your Data Here, it can be an object if need be');
    this.modalClose.complete();
  }

并且您的模态服务可以访问onModalClose().subscribe()方法中的数据:

componentRef.instance.onModalClose().subscribe((results) => {
  console.log(results);
  console.log('I will be very happy if this this gets called, but it never ever does');
  this.closeModal();
});
点赞