angular6 - Angular 6订阅构造函数上的事件多次调用
问题描述
在我的构造函数组件(子组件)中,我添加了简单事件
这是我的代码:
this._modalService.onHidden.subscribe(
result => {
console.log("_modalService.onHidden");
if(this.shown){
this.shown = false;
this._router.navigate(['.'], { relativeTo: this._route.parent });
}
}, error => console.log(error));
第一次打开此页面时,此事件仅调用一次,但再次进入页面时,此事件调用了两次,进入 3 次时,此事件调用了 3 次,依此类推。
[顺便说一句,如果我将代码移动到 ngOnInit 事件上也会发生这种情况,并且这种情况也会发生在另一个事件 ngrx 存储管道上,该事件多次调用]
这是我的路线(也许是原因)
const routes: Routes = [
{
path:':id' ,component:EventComponent,
children:[
{
path:'o/:file'
,component:EventDetailComponent
}]
},
{
path:':id/:sub' ,component:EventComponent,
children:[{
path:'o/:file'
,component:EventDetailComponent
}]
}
];
解决方案
你应该取消订阅OnDestroy
...
在构造函数中:
this.mySubscription = this._modalService.onHidden.subscribe(...);
在onDestroy
:
this.mySubscription.unsubscribe();
推荐阅读
- xamarin - Xamarin form appcenter PushNotificationReceived 方法在应用程序被终止时用户单击通知时不运行
- r - 通过重复值对 data.table 进行子集
- c# - Azure 错误,找不到 Internet Explorer
- java - 如果我通过 spark-submit 将非 spark jar 提交到集群会发生什么?
- c - 仅将 char 压缩为两位
- java - java.lang.RuntimeException:清单合并失败,出现多个错误,请参阅日志
- python - 如何使用 Featuretools 按列值从单个数据框中的多列创建特征?
- html - Bootstrap 并排网格视图
- r - 在 R 中有效地呈现非常小的数字
- python - python根据另一列的条件在数据框中添加行