Angular-如何持续调用和API(2秒内2次)

时间:2018-10-30 14:59:53

标签: angular api

我想每2秒调用一次我的API,以了解我的后端是否正在运行。

我的后端服务:

getMasterInfo()
{
    return this.http.get('http://localhost:8080/pe/info');
}

我的组件

onGet() {
this.waitingAgent = "true";
this.waitingMaster = "true";


this.backend.getMasterInfo().subscribe(
  (response: Response) => {
    this.dataMaster = response.json();
    console.log(this.dataMaster.status);
    this.waitingMaster = "false";
    this.activeMaster = "true";
    this.httperrorMaster = "false";
  },
  (error) => {
    console.log("Erro: " + error);
    this.waitingMaster = "false";
    this.httperrorMaster = "true";
    this.activeMaster = "false";
  } 
);

也许使用.repeat().retry().distinctUntilChanged()之类的东西可以解决此问题?

2 个答案:

答案 0 :(得分:1)

因此,我通过添加一个setInterval()来解决此问题,例如每5秒调用一次api。

setInterval(() => {
  this.onGet();
}, 5000);

所以我在init上调用我的函数来第一次进入api,然后设置一个间隔来调用该函数,如下所示:

ngOnInit() {

    this.onGet();

    setInterval(() => {
      this.onGet();
    }, 5000);
}

答案 1 :(得分:-1)

更好的方法是使用Observable.Interval而不是setInterval。

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';


  ngOnInit() {
    this.callEvery2Seconds();
  }

public callEvery2Seconds() {
    Observable
      .interval(2000)
      .subscribe(
        x => this. onGet();
      );
  }
}
相关问题