使用Angular HTTP Observable的轮询API [英] Poll API using Angular HTTP Observable

查看:128
本文介绍了使用Angular HTTP Observable的轮询API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组件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可以根据要求进行更改. intervalswitchMap应该按以下方式导入:

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的轮询API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆