2

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

2 Answers 2

3

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 => {});
Sign up to request clarification or add additional context in comments.

1 Comment

It works well but when there is some error in the http api the whole interval breaks and it no longer repeats.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.