如何使用setInterval以角度调用我的服务

时间:2020-08-26 07:11:57

标签: javascript angular setinterval

我有一个服务,该服务会在页面加载时返回一些数据,

getAllTurbinesStat(){
  return this.http.get(this.url_stat_Turbines_all);
}

我在组件中使用此服务:

this.service.getAllTurbinesStat().subscribe( s => {
   this.allStats.push(s);
});

allStat是一个数组,现在每3分钟应运行此函数以更新数据,setInterval是在使用中还是在我的组件中?我该怎么写呢?因为第一次我不需要setinterval,因为第一次加载页面后,我的数据就会更新。

4 个答案:

答案 0 :(得分:2)

您可以尝试一下。

首先像这样在您的组件中创建一个函数。

getAllTurbinesStat() {
  this.service.getAllTurbinesStat().subscribe(s => {
    this.allStats.push(s);
  });
}

然后在组件的ngOnInit()constructor中使用它。

this.getAllTurbinesStat();
setInterval(() => this.getAllTurbinesStat(), 180000);

答案 1 :(得分:1)

您可以像下面这样使用间隔:

为您服务

 getAllTurbinesStat(){
  return this.http.get(this.url_stat_Turbines_all);
 }

 getData(): {
   return interval(3000).pipe(
      switchMap( () => this.getAllTurbinesStat())
   )

 }

在您的组件中

this.service.getData().subscribe( s => {
   this.allStats.push(s);
});

答案 2 :(得分:1)

您可以使用rxjs中的计时器。

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

根据您的情况。

  return timer(0, 180000).pipe(
      flatMap( () => this.getAllTurbinesStat())
   )

答案 3 :(得分:1)

首先在组件的ngOnInit中调用一次函数,然后继续使用setInterval

ngOnInit() {
   getAllTurbinesStat();
   setInterval(getAllTurbinesStat(), 3000);
}

getAllTurbinesStat() {
  return this.http.get(this.url_stat_Turbines_all);
}