-1

I have an Angular 6 project that displays the status of a process that is running on backend server. My first idead was to call the backend API every 2 seconds to refresh the status of the process like this:

My service that communicates with the backend:

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

My component:

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

Maybe using something like .repeat() , .retry() or .distinctUntilChanged() will solve this problem? I don't know how to correctly refresh the status.

Kiril1512
  • 3,231
  • 3
  • 16
  • 41
  • This might help you https://stackoverflow.com/questions/42557993/how-do-i-stop-observable-timer-or-observable-interval-automatically-after-ce It runs every 5 seconds for 1 minute – Amit Chigadani Oct 30 '18 at 15:08
  • I would use intervall() from rxjs 6. See the following link for an example: [link](https://www.learnrxjs.io/operators/creation/interval.html) Link2 describes the same with timer() from rxjs 6: [link2](https://stackoverflow.com/questions/36612945/how-to-get-an-observable-to-return-data-immediately-and-every-5-seconds-thereaft) – student18 Oct 30 '18 at 15:09

2 Answers2

2

So I resolved this by adding a setInterval() that calls my api every 2 seconds like:

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

So I call my function on init to get to the API for the first time and then set a interval to call the function like following:

ngOnInit() {  
    this.onGet();

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

Update: After some research I realized that this is provably not the best approach for this problem. In cases like this, when the server needs to notificate the client when an update occurs is better that the server sends an event to the client and not the client constantly ask for updates. The best aproach will be create for example a WebSocket connection between those two and broadcast real time data to the client.

Kiril1512
  • 3,231
  • 3
  • 16
  • 41
0

A better way is using Observable.Interval instead of setInterval.

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


  ngOnInit() {
    this.callEvery2Seconds();
  }

public callEvery2Seconds() {
    Observable
      .interval(2000)
      .subscribe(
        x => this. onGet();
      );
  }
}
NgoCuong
  • 2,169
  • 1
  • 11
  • 9