繁体   English   中英

移动到另一个菜单时销毁 Angular 5 组件

[英]Destroy Angular 5 components when move to another menu

我有一个具有行为主题订阅的报告组件,它在 .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();
              };
            });
          }
        };
      }
    };
}

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

您可以使用 OnDestroy 生命周期钩子取消订阅页面销毁时的行为主题,如下所示

this.sub_State = this.stateService.showStateBehaviorSubject.subscribe((state: boolean) => {
            this.showState = state;
        });
ngOnDestroy() {
        this.sub_State .unsubscribe();
    }

创建一个主题属性并获取订阅,直到它在 ngDestroy 中被销毁

class MyComponent {
  destroyed$ = new Subject();

  ngOnDestroy() {
    this.destroyed$.next();
  }

  myMethod() {
   this.apiHelper.get('some/url')
     .pipe( takeUntil(this.destroyed$) )
     .subscribe(()=> {
       // do things
     });
  }
}

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

this.data$ = this.reportService.behaviourSubjectObj

在您的模板中:

{{ data$ | async | json }}

使用 ComponentRef ,如果你想从父级销毁它,请按照下面的代码

@ViewChild(ChildComponent, { read: ComponentRef }) childComponentRef: ComponentRef;

电话

this.childComponentRef.destroy()

在 parent 的事件中起作用。

参考这个链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM