首页 > 解决方案 > 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
    }]
  }
];

在此处输入图像描述

标签: angular6angular-routingngrxngrx-storeangular-lifecycle-hooks

解决方案


你应该取消订阅OnDestroy...

在构造函数中:

this.mySubscription = this._modalService.onHidden.subscribe(...);

onDestroy

this.mySubscription.unsubscribe();


推荐阅读