How To Do Polling with Angular 2 Observables

2019-02-04 12:57发布

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));
    }
}

4条回答
放我归山
2楼-- · 2019-02-04 13:09

Why not try setInterval()?

setInterval(getFooBars(), 500);
查看更多
Ridiculous、
3楼-- · 2019-02-04 13:11

Try this

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url).map(res:Response => res.json()));
查看更多
疯言疯语
4楼-- · 2019-02-04 13:25

make sure you have imported import {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();
}
}
查看更多
仙女界的扛把子
5楼-- · 2019-02-04 13:29

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.

查看更多
登录 后发表回答