Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I poll a service using RXJS Observables?

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));
    }
}
like image 263
Jerry Huckins Avatar asked Jan 15 '17 05:01

Jerry Huckins


People also ask

What is polling in angular?

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.

How do you poll in JavaScript?

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.

What are RxJS observables?

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.

What is long polling?

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.


2 Answers

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();
}
}
like image 188
Amit kumar Avatar answered Sep 20 '22 22:09

Amit kumar


Try this

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url).map(res:Response => res.json()));
like image 22
Rahul Singh Avatar answered Sep 16 '22 22:09

Rahul Singh