如何使用 setInterval 在 angular 中调用我的服务

how to call my service in angular using setInterval

我有一项服务可以在页面加载时获取 returns 一些数据,

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

在我的组件中我使用了这个服务:

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

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

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

为您服务

 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);
});

你可以试试这个。

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

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

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

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

您可以使用 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())
   )

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

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

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