如何使用Angular 2 Observable进行轮询

时间:2017-01-15 05:37:19

标签: angular observable polling

鉴于以下代码,如何更改它以向" api / foobar"每500毫秒重复一次?

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 个答案:

答案 0 :(得分:33)

确保从'rxjs / Rx'导入导入{Observable}如果我们不导入它我们得到可观察到的错误有时候

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

答案 1 :(得分:2)

试试这个

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

答案 2 :(得分:2)

我推荐rx-polling库,它提取了大量详细信息,提供了重试,退避策略的机制,甚至在浏览器选项卡变为非活动状态时暂停/恢复。

答案 3 :(得分:-4)

为什么不试试setInterval()?

setInterval(getFooBars(), 500);