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.