完成后n秒重复请求(Angular2 - http.get) [英] Repeat request (Angular2 - http.get) n seconds after finished
问题描述
我玩了angular2并且在一段时间后陷入困境。
I played around with angular2 and got stuck after a while.
使用 http.get
工作正常一个请求,但我想每4秒轮询一次实时数据,经过一段时间的修补和读取很多反应性的东西我最终得到:
Using http.get
works fine for a single request, but I want to poll live-data every 4 seconds, after tinkering for quite a while and reading a lot of reactivex stuff i ended up with:
Observable.timer(0,4000)
.flatMap(
() => this._http.get(this._url)
.share()
.map(this.extractData)
.catch(this.handleError)
)
.share();
是否有简单方式开始(4秒)间隔后 http.get
-observable发出了请求的结果? (或者我最终会在 observable-hell ?)
Is there a simple way to start a (4 second) interval after the http.get
-observable has emitted the result of the request? (Or will I end up in observable-hell?)
我想要的时间表:
Time(s): 0 - - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - 5 - - - - - 6
Action: Request - - Response - - - - - - - - - - - - - - - - - - - -Request-...
Wait: | wait for 4 seconds -------------------------> |
推荐答案
更新至RxJS 6
import { timer } from 'rxjs';
import { concatMap, map, expand, catchError } from 'rxjs/operators';
pollData$ = this._http.get(this._url)
.pipe(
map(this.extractData),
catchError(this.handleError)
);
pollData$.pipe(
expand(_ => timer(4000).pipe(concatMap(_ => pollData$)))
).subscribe();
我正在使用RxJS 5而我是不确定RxJS 4等效运算符是什么。无论如何这里是我的RxJS 5解决方案,希望它有所帮助:
I'm using RxJS 5 and I'm not sure what the RxJS 4 equivalent operators are. Anyway here is my RxJS 5 solution, hope it helps:
var pollData = this._http.get(this._url)
.map(this.extractData)
.catch(this.handleError);
pollData.expand(
() => Observable.timer(4000).concatMap(() => pollData)
).subscribe();
扩展运算符将发出数据并以每次发射递归启动一个新的Observable
The expand operator will emit the data and recursively start a new Observable with each emission
这篇关于完成后n秒重复请求(Angular2 - http.get)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!