gpt4 book ai didi

angular - 如何使用 RXJS Observables 轮询服务?

转载 作者:太空狗 更新时间:2023-10-29 16:56:06 26 4
gpt4 key购买 nike

给定以下代码,我如何更改它以使对“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));
}
}

最佳答案

确保您已经从 rxjs/Rx 导入了 {Observable}。如果我们不导入它,有时会出现可观察到的未找到错误。

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

关于angular - 如何使用 RXJS Observables 轮询服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41658162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com