代码之家  ›  专栏  ›  技术社区  ›  24sharon

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

  •  0
  • 24sharon  · 技术社区  · 6 年前

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

    这是我的代码:

    this.\modalservice.onhidden.subscribe(
    结果=& gt;{
    console.log(“modalservice.onhidden”);
    如果(如图所示){
    this.shown=false;
    this._router.navigate(['],relativeto:this._route.parent);
    }
    },错误=>console.log(错误));
    < /代码> 
    
    

    在第一次打开此页时,此事件仅调用了一个 但当再次进入页面时,此事件调用了两次 当输入3次时,此事件称为3次等。

    [btw如果我移动ngoninit事件上的代码,也会发生这种情况 这也发生在另一个事件ngrx存储管道上,该事件调用了多次

    这是我的路线(也许是原因)

    const routes:routes=[
    {
    路径:“:id”,组件:eventcomponent,
    孩子:[
    {
    路径:“o//文件”
    ,组件:EventDetail组件
    }
    },请
    {
    路径:“:id/:sub”,组件:eventcomponent,
    孩子:【1】{
    路径:“o//文件”
    ,组件:EventDetail组件
    }
    }
    ;
    < /代码> 
    
    

    =

    在第一次打开此页时,此事件仅调用了一个 但当再次进入页面时,此事件调用了两次 当输入3次时,此事件称为3次等。

    [btw如果我移动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
        }]
      }
    ];
    

    1 回复  |  直到 6 年前
        1
  •  1
  •   tlt    6 年前

    你应该退订 OnDestroy

    在构造函数中:

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

    在里面 onDestroy 以下内容:

    this.mySubscription.unsubscribe();