How To Do Polling with Angular 2 Observables
Make sure you have imported {Observable}
from rxjs/Rx
. If we don't import it we get observable not found error sometimes.
Working plnkr http://plnkr.co/edit/vMvnQW?p=preview
import {Component} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'app',
template: `
<b>Angular 2 HTTP polling every 5 sec RxJs Observables!</b>
<ul>
<li *ngFor="let doctor of doctors">{{doctor.name}}</li>
</ul>
`
})
export class MyApp {
private doctors = [];
pollingData: any;
constructor(http: Http) {
this.pollingData = Observable.interval(5000)
.switchMap(() => http.get('http://jsonplaceholder.typicode.com/users/')).map((data) => data.json())
.subscribe((data) => {
this.doctors=data;
console.log(data);// see console you get output every 5 sec
});
}
ngOnDestroy() {
this.pollingData.unsubscribe();
}
}
Try this
return Observable.interval(2000)
.switchMap(() => this.http.get(url).map(res:Response => res.json()));
I recommend the rx-polling library which abstracts a lot of the details provides mechanisms for retries, back-off strategies, and even pause/resume if browser tab becomes inactive.