MFB
MFB

Reputation: 19807

Poll API using Angular HTTP Observable

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

Upvotes: 2

Views: 3293

Answers (2)

siva636
siva636

Reputation: 16441

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

Upvotes: 2

khush
khush

Reputation: 2801

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

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

Upvotes: 0

Related Questions