【问题标题】:Angular 6 subscribe Event on constructor called multiple timesAngular 6订阅构造函数上的事件多次调用
【发布时间】:2019-04-21 11:04:15
【问题描述】:

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

这是我的代码:

   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
    }]
  }
];

【问题讨论】:

    标签: angular6 angular-routing ngrx ngrx-store angular-lifecycle-hooks


    【解决方案1】:

    你应该取消订阅OnDestroy...

    在构造函数中:

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

    onDestroy:

    this.mySubscription.unsubscribe();

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多