Angular2 refresh API every x minutes to watch change in response

1.2k views Asked by At

Is there a way, in Angular 2, to watch for change in API.

Here is my case:

  • I push a document to an API /document/upload
  • This API return a DOC id
  • Using a call to /document/DOC_ID, the API returns a JSON in this format:
"errorCode":0,

"docId":"585846a1afe8ad12e46a4e60",

"status":0

Status can be:

  • 0 = pending
  • 1 = signed
  • 2 = validated

This status will be "changed" by a worker on the remote server which validate the file. This state is only "interrogated" through the API.

On my front-end, I've a component dedicated to display the state of my document:

<p>Current State: {fileState}</p>

On my component, how can i watch the change of status in the api call result : how can I place for example a call which will call the API every x minutes to verify the state and update the view accordingly?

1

There are 1 answers

0
Sasxa On BEST ANSWER

You can write something like this:

checkStatus(minutes: number, docID: string) {
  Observable.interval(minutes * 60 * 1000)
    .switchMap(() => this.http.get(`/documents/${docID}`)
      // handle http errors here to prevent
      // breaking of interval observable
      .catch(error => Observable.of(error))
      .map(response => response.json())
    .subscribe(data => {
      this.fileState = 
        data.state === 0 ? 'pending' : 
        data.state === 1 : 'signed' : 'validated';
    })
}

Don't forget to import observable operators:

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';