简体   繁体   English

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

[英]refreshing data on page every X seconds for angular component

I need to refresh data of angular component each 30 seconds.我需要每 30 秒刷新一次角度组件的数据。 I use simple setInterval :我使用简单的setInterval

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

However, this is incorrect, because even when I navigate to another "page" (in angular SPA everything is one page, so it is not really another page), refresh is happening each 30 seconds.但是,这是不正确的,因为即使我导航到另一个“页面”(在 Angular SPA 中,所有内容都是一页,因此它实际上不是另一页),每 30 秒刷新一次。

What is the correct way to refresh data every 30 seconds only when on specific page/component?仅在特定页面/组件上每 30 秒刷新一次数据的正确方法是什么?

You could destroy interval on OnDestroy life cycle hook of the component.您可以在组件的OnDestroy生命周期挂钩上销毁时间间隔。

Using clearInterval(this.interval)使用clearInterval(this.interval)

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

You could clearInterval in ngOnDestroy life cycle hook of component您可以在组件的ngOnDestroy生命周期钩子中ngOnDestroy

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

ngOnDestroy will call every time component destroy in digest cycle and it will clear your interval as well (If you do so). ngOnDestroy将在摘要循环中每次销毁组件时调用,它也会清除您的间隔(如果您这样做)。 Generally used to call logic which we don't require after navigation of current route to another.通常用于在当前路线导航到另一个之后调用我们不需要的逻辑。

try this.尝试这个。

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

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

When you navigate to another page, you have to clear the interval you are setting.当您导航到另一个页面时,您必须清除您设置的间隔。

this.interval = setInterval(()=>{
  ...
});

navigateToAnotherPage = () => {
  //function to navigate to another page
  clearInterval(this.interval);
  router.navigate(...)//if you are using router to navigate
}

try this.尝试这个。

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

        }, 1000);
}

You can also leverage reactive style.您还可以利用反应式风格。

import { timer } from 'rxjs';
/*
  timer takes a second argument, how often to emit subsequent values
  in this case we will emit first value after 1 second and subsequent
  values every 2 seconds after
*/
const source = timer(0, 2000);
//output: 0,1,2,3,4,5......
const subscribe = source.subscribe(val => console.log(val));

Reference - https://www.learnrxjs.io/learn-rxjs/operators/creation/timer参考 - https://www.learnrxjs.io/learn-rxjs/operators/creation/timer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM