【问题标题】:End interval when route changes in Angular 2Angular 2中路线更改时的结束间隔
【发布时间】:2016-02-22 18:40:08
【问题描述】:

我在路由器插座内的 Angular 2 组件中启动了一个计时器。

setInterval(() => {
    ...
}, 10000);

当我离开嵌入组件的路线时,计时器不会退出。我怎样才能做到这一点?

【问题讨论】:

    标签: javascript angular typescript angular2-routing


    【解决方案1】:

    你可以从这个钩子中清除间隔。 我的是从组件/视图控制的。

    export classTestInterval implements OnInit, OnDestroy{
         public timerInterval:any;
         ngOnInit(){
           // Need interval scope in the component could be from somewhere else, but we need scope to be able to clear it on destruction of component.
           this.timerInterval = setInterval(function(){...},10000);
         }
         ngOnDestroy() {
            // Will clear when component is destroyed e.g. route is navigated away from.
            clearInterval(this.timerInterval);
         }
    }
    

    【讨论】:

      【解决方案2】:

      应该这样做:

      routerOnActivate() {
        this.timer = setInterval(()=>{
                      ...
                  }, 10000);
      }
      
      routerOnDeactivate() {
        clearInterval(this.timer);
      }
      

      【讨论】:

        【解决方案3】:

        也许你想要的更好OnDeactivate 来自angular2/router(也可能是OnActivate,具体取决于你的用例)因为你说你想在用户离开路线时结束计时器如果我理解正确的话。

        export Compnent implements OnInit, OnDeactivate {
            private timer;
        
            ngOnInit(){
                this.timer = setInterval(_ => {
                    // disco
                }, 10000);
            }
        
            routerOnDeactivate() {
                clearInterval(this.timer);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-24
          • 1970-01-01
          • 1970-01-01
          • 2016-12-22
          • 2019-07-16
          • 1970-01-01
          • 2022-07-27
          • 2017-07-28
          • 2016-05-10
          相关资源
          最近更新 更多