angular - 移动到另一个菜单时销毁 Angular 5 组件
问题描述
我有一个报告组件,它订阅了 Behavior Subject 并在 .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();
};
});
}
};
}
};
}
它应该取消订阅;但是,所有订阅也会在导航到其他页面后执行。
解决方案
只需使用async
管道即可在模板上显示数据,而无需订阅 BehaviorSubject。
this.data$ = this.reportService.behaviourSubjectObj
在您的模板中:
{{ data$ | async | json }}
推荐阅读
- angular - Angular 指令创建重复元素
- string - Raku:从字符串中捕获组的一行表达式?
- java - 当使用“ON DUPLICATE KEY UPDATE”批量插入的 PK 中两条记录重复时会发生什么
- nginx - Nginx S3 代理:尝试在第一个 404 上提供 index.html
- performance - 使用 Kafka 和 Storm 进行负载测试
- node.js - const 未在 nodejs 中定义导致单元测试失败
- nuget-package - 如何解决:Nuget Visual Studio 2019 消息 Project 'Default' not found
- python - 尝试/除未按预期工作:“Except”错误消息附加到传递结果
- laravel - 在 Laravel 中存储 App Key 的最佳实践
- json - JSONB 数组输出 - Postgres 11.5