Is there a way, in Angular 2, to watch for change in API.
Here is my case:
"errorCode":0, "docId":"585846a1afe8ad12e46a4e60", "status":0
Status can be:
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?
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';