skip to Main Content

Using
ANGULAR

I would like http.get to frequently pull data from an API, and can’t find a viable solution. The API is providing minute by minute traffic data, and I would like Angular to reflect the updates.

At the moment i am using interval from rxjs to refresh the Get request, but that’s crashing the browser. This turns out, is not a suitable way do get this done. It is memory intensive.

interval(3000).subscribe(x => { http.get('api.link')});

What solution is there that I could get this done conservatively ?

2

Answers


  1. i handle these situations with following code:

    interval(3000).pipe(
      map(() => this.http.get('apiUrl')),
      mergeMap(x => x)
    ).subscribe(res => {
      console.log(res);
    });
    
    Login or Signup to reply.
  2. Probably the request sometimes takes more than 3 sec.

    You need to use concatMap to ensure that the next request will only be fired after the current one is completed, ensuring that requests do not overlap

    interval(3000).pipe(
          concatMap(() => this.http.get('api.link'))
        ).subscribe({
          next: (data) => {
            // Handle the incoming data
          },
          error: (error) => {
            // Handle any error
          }
        });
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search