鉴于以下代码,如何更改它以使得“api / foobar”的get请求每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)); } }
确保你从’rxjs / Rx’导入导入{Observable}如果我们不导入它我们得到可观察到的错误有时会发现错误
原文链接:https://www.f2er.com/angularjs/143782.html工作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(); } }