【问题标题】:Poll API using Angular HTTP Observable使用 Angular HTTP Observable 轮询 API
【发布时间】:2018-12-05 21:50:37
【问题描述】:

在我的组件 html 中,我使用 asyncPipe 订阅此 http 服务。该服务将 json 响应对象映射到类实例数组。这一切都很好,但我希望 http 服务每隔几秒钟轮询一次。我已经尝试了很多东西(比如间隔),但目前看来 RXJS 有点雷区。有没有人使用 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)
      );
  }

【问题讨论】:

    标签: angular typescript rxjs angular-httpclient


    【解决方案1】:

    这应该像下面这样简单:

        pollInterval = 5000;
        const httpObservable = interval(pollInterval).pipe(
        switchMap(x => fetch(command, params?) )
       );
    

    pollInterval 可以根据需要更改。 intervalswitchMap 应按如下方式导入:

    import { interval } from 'rxjs';
    import { switchMap } from 'rxjs/operators'; 
    

    在此处使用switchMap 有助于取消任何延迟的待处理http 请求,这对性能有好处,尤其是在间歇性互联网连接期间。这就是为什么 RxJS 的响应式方法比 setInterval() 等传统方法更受欢迎的原因。

    最后也要订阅,否则什么都不会发生:

    httpObservable.subscribe(x => {});
    

    【讨论】:

    • 它运行良好,但是当 http api 出现错误时,整个间隔中断并且不再重复。
    【解决方案2】:

    如果你不想使用 rxjs 也可以这样做

     setInterval(function(){
          serviceObj.httpObservable.subscribe(x => {});
        }, 10000)
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2017-10-18
      • 2018-02-14
      • 1970-01-01
      • 2021-11-08
      • 2018-01-07
      相关资源
      最近更新 更多