How To Do Polling with Angular 2 Observables

安稳与你 提交于 2019-11-27 13:55: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));
    }
}

回答1:


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



回答2:


Try this

return Observable.interval(2000) 
        .switchMap(() => this.http.get(url).map(res:Response => res.json()));



回答3:


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.




回答4:


Why not try setInterval()?

setInterval(getFooBars(), 500);


来源:https://stackoverflow.com/questions/41658162/how-to-do-polling-with-angular-2-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!