首页 > 解决方案 > 移动到另一个菜单时销毁 Angular 5 组件

问题描述

我有一个报告组件,它订阅了 Behavior Subject 并在 .next 调用之后从 web api 中提取数据。当我在报告页面后移动到另一个页面时,报告组件仍然存在并不断向 webApi 发送调用。

如何在导航到另一个或取消订阅行为主题后销毁组件。更多细节。我的报表组件很少,它呈现不同类型的报表。其中一个组件如下

@destroyAllSubscribers()
    export class StandardReportComponent implements OnInit {

    public subscriptions: Subscription[] = [];
    reportData = [];
    showReport=false;
    constructor(private reportService: ReportService)
    {

        this.subscriptions.push(this.reportService.chartType.subscribe(chartType => {

        if (this.currentChart != ReportChartType.None){

         this.showReport=false;  //Used in *ngIf to show report HTML template
            this.reportService.getReportData().subscribe(result=>{
        this.reportData=result; 
        this.showReport=true; //Used in *ngIf to show report HTML template


    }

    }

    }
    }

我有销毁订阅者装饰器,它在组件销毁时执行,

代码:

export function destroyAllSubscribers() {
    return (targetComponent: any) => {
      targetComponent.prototype.ngOnDestroy = ngOnDestroyDecorator();

      function ngOnDestroyDecorator() {
        return function () {
          if (this.subscriptions != undefined)
          {
            this.subscriptions.forEach(subscription => {
              if (subscription instanceof Subscriber) {
                subscription.unsubscribe();
              };
            });
          }
        };
      }
    };
}

它应该取消订阅;但是,所有订阅也会在导航到其他页面后执行。

标签: angularangular5behaviorsubject

解决方案


只需使用async管道即可在模板上显示数据,而无需订阅 BehaviorSubject。

this.data$ = this.reportService.behaviourSubjectObj

在您的模板中:

{{ data$ | async | json }}

推荐阅读