Poll API using Angular HTTP Observable

拟墨画扇 提交于 2020-01-23 12:26:05

问题


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)
      );
  }

回答1:


This should be as simple as the following:

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

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'; 

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 => {});



回答2:


You can also do like this if you dont want to use rxjs

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


来源:https://stackoverflow.com/questions/51055339/poll-api-using-angular-http-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!