代码之家  ›  专栏  ›  技术社区  ›  renathy Jayant Varshney

角组件每X秒刷新一次页面上的数据

  •  1
  • renathy Jayant Varshney  · 技术社区  · 6 年前

    我需要每30秒刷新一次角度分量的数据。我用简单的 setInterval

     this.interval = setInterval(() => {
                   this.refresh(); // api call
                }, 10000);
    

    然而,这是不正确的,因为即使我导航到另一个“页面”(在angular SPA中,所有内容都是一个页面,因此它实际上不是另一个页面),刷新也会每30秒发生一次。

    4 回复  |  直到 6 年前
        1
  •  6
  •   ptesser    6 年前

    你可以把间隔时间毁了 OnDestroy

    使用 clearInterval(this.interval)

    ngOnDestroy() {
       if (this.interval) {
         clearInterval(this.interval);
       }
    }
    
        2
  •  1
  •   Pardeep Jain    6 年前

    ngOnDestroy 组件的生命周期挂钩

    ngOnDestroy() {
      clearInterval(this.interval);
    }
    

    恩戈德斯特罗 通常用于在当前路线导航到另一条路线后调用我们不需要的逻辑。

        3
  •  0
  •   Farhat Zaman    6 年前

    routerOnActivate() {
       this.interval = setInterval(() => {
                   this.refresh(); // api call
                }, 10000);
    }
    
    routerOnDeactivate() {
      clearInterval(this.interval);
    }
    
        4
  •  0
  •   lloydaf    6 年前

    当您导航到另一页时,必须清除正在设置的间隔。

    this.interval = setInterval(()=>{
      ...
    });
    
    navigateToAnotherPage = () => {
      //function to navigate to another page
      clearInterval(this.interval);
      router.navigate(...)//if you are using router to navigate
    }
    
        5
  •  0
  •   Fahimeh Ahmadi    4 年前

    save: boolean = false;
    autoSave() {
            setInterval(() => {
                console.log('setTimeOut');
                this.save = true;
    
            }, 1000);
    }