Given the following code, how to I alter it to make the get request to "api/foobar" repeat every 500 milliseconds?
import {Observable} from "RxJS/Rx";
import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
@Injectable() export class ExampleService {
constructor(private http: Http) { }
getFooBars(onNext: (fooBars: FooBar[]) => void) {
this.get("api/foobar")
.map(response => <FooBar[]>reponse.json())
.subscribe(onNext,
error =>
console.log("An error occurred when requesting api/foobar.", error));
}
}
Polling is a process by which the client continuously request data from the server without any user interaction. It is mainly used to track the long running back-end process status.
const poll = async function (fn, fnCondition, ms) { let result = await fn(); while (fnCondition(result)) { await wait(ms); result = await fn(); } return result; }; const wait = function (ms = 1000) { return new Promise(resolve => { setTimeout(resolve, ms); }); }; let fetchReport = () => axios.
RxJS introduces Observables, a new Push system for JavaScript. An Observable is a Producer of multiple values, "pushing" them to Observers (Consumers). A Function is a lazily evaluated computation that synchronously returns a single value on invocation.
Start Learning. HTTP Long Polling is a technique used to push information to a client as soon as possible on the server. As a result, the server does not have to wait for the client to send a request. In Long Polling, the server does not close the connection once it receives a request from the client.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With