使用 Angular HTTP Observable 的 Poll API [英] Poll API using Angular HTTP Observable
问题描述
在我的组件 html 中,我使用 asyncPipe 订阅此 http 服务.该服务将 json 响应对象映射到类实例数组.这一切都很好,但我希望 http 服务每隔几秒轮询一次.我已经尝试了很多东西(比如间隔),但目前 RXJS 似乎有点雷区.有没有人用 Angular 6 实现过这种东西?
In my component html, I am using the asyncPipe to subscribe to this http service. The service maps the json response object to an array of class instances. This all works great, but I would like http service to poll every few seconds. I've tried a bunch of things (like interval), but it seems RXJS is a bit of a minefield at the moment. Has anyone implemented this kind of thing using Angular 6?
fetch(command, params?) {
return this.http.post(`http://localhost:4000/${command}`, params)
.pipe(
map((data: Data) => {
const statuses: Status[] = [];
for (const statusKey of Object.keys(data.statuses)) {
const newStatus = new Status(
// do some object translation...
);
statuses.push(newStatus);
}
return statuses;
})
)
.pipe(
catchError(EpisodeApiService.handleError)
);
}
推荐答案
这应该像下面这样简单:
This should be as simple as the following:
pollInterval = 5000;
const httpObservable = interval(pollInterval).pipe(
switchMap(x => fetch(command, params?) )
);
pollInterval
可以根据需求进行更改.interval
和 switchMap
应按如下方式导入:
The pollInterval
may be changed according to the requirements. interval
and switchMap
should be imported as follows:
import { interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';
在此处使用 switchMap
有助于取消任何延迟的未决 http 请求,这对性能有好处,尤其是在间歇性 Internet 连接期间.这就是为什么 RxJS 响应式方法比 setInterval()
等传统方法更受欢迎的原因.
Using switchMap
here helps to cancel any delayed pending http requests, this is good for performance particularly during intermittent Internet connections. That is why the RxJS reactive way of doing this is preferred over traditional methods such as setInterval()
.
最后还要订阅,否则什么都不会发生:
Also a subscription should be made finally, otherwise nothing will happen:
httpObservable.subscribe(x => {});
这篇关于使用 Angular HTTP Observable 的 Poll API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!