How To Do Polling with Angular 2 Observables

前端 未结 4 570
长情又很酷
长情又很酷 2020-12-14 08:53

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\";
im         


        
相关标签:
4条回答
  • 2020-12-14 09:09

    Why not try setInterval()?

    setInterval(getFooBars(), 500);
    
    0 讨论(0)
  • 2020-12-14 09:13

    Try this

    return Observable.interval(2000) 
            .switchMap(() => this.http.get(url).map(res:Response => res.json()));
    
    0 讨论(0)
  • 2020-12-14 09:17

    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.

    0 讨论(0)
  • 2020-12-14 09:20

    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();
    }
    }
    
    0 讨论(0)
提交回复
热议问题