【发布时间】:2018-09-19 06:33:36
【问题描述】:
我有一个报告组件,它订阅了行为主题,它在 .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();
};
});
}
};
}
};
}
它应该取消订阅;但是所有订阅也会在导航到其他页面后执行。
【问题讨论】:
-
请为您的
ReportComponent发布一些代码以使其清楚。 -
export class ReportComponent { constructor(private reportService: ReportService) this.chartService.currentDates.subscribe(date => { //从web API获取数据 }); } }
-
我已经粘贴了示例代码,希望对您有帮助
标签: angular angular5 behaviorsubject