简体   繁体   English

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

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

I have a report component which have Behavior Subject subscription and it pull data from web api after .next call.我有一个具有行为主题订阅的报告组件,它在 .next 调用后从 web api 中提取数据。 When I am move to another page after report page, report component still alive and keeps sending calls to webApi.当我在报告页面之后移动到另一个页面时,报告组件仍然存在并不断向 webApi 发送调用。

How to destroy components after navigate to another or unsubscribe Behavior Subjects.导航到另一个或取消订阅行为主题后如何销毁组件。 More details.更多细节。 I have few report components, it renders different type of reports.我的报告组件很少,它呈现不同类型的报告。 One of the component is below组件之一如下

@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


    }

    }

    }
    }

I have destroy subscriber decorator which gets executed when component destroys,我已经销毁了在组件销毁时执行的订阅者装饰器,

Code:代码:

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

It should unsubscribe;它应该退订; however all subscription gets executed after navigate to other page as well.但是所有订阅也会在导航到其他页面后执行。

You can unsubscribe the Behavior Subjects at page destroy using OnDestroy life cycle hook like this您可以使用 OnDestroy 生命周期钩子取消订阅页面销毁时的行为主题,如下所示

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

Create a Subject property and take the subscription until it's destroyed in ngDestroy创建一个主题属性并获取订阅,直到它在 ngDestroy 中被销毁

class MyComponent {
  destroyed$ = new Subject();

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

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

Simply use async pipe to display the data on the template without having to subscribe to the BehaviorSubject.只需使用async管道在模板上显示数据,而无需订阅 BehaviorSubject。

this.data$ = this.reportService.behaviourSubjectObj

In your template:在您的模板中:

{{ data$ | async | json }}

Use ComphonentRef , if you want to destroy it from parent then follow the below code使用 ComponentRef ,如果你想从父级销毁它,请按照下面的代码

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

the call电话

this.childComponentRef.destroy() this.childComponentRef.destroy()

function in an event of parent .在 parent 的事件中起作用。

refer this link参考这个链接

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

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