简体   繁体   中英

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. When I am move to another page after report page, report component still alive and keeps sending calls to 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

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

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.

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

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

the call

this.childComponentRef.destroy()

function in an event of parent .

refer this link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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