Angular 6 多次调用构造函数上的订阅事件

Angular 6 subscribe Event on constructor called multiple times

在我的构造函数组件(子组件)中,我添加了简单的事件

这是我的代码:

   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();