user3739018
user3739018

Reputation: 2519

Need to make multiple async call to the same endpoint in Angular 8

I have a get call which accepts only one search number and returns the result. I have a requirement where I need to search with multiple numbers using the same GET call. I know it can be achieved by opening new endpoint with POST call but unfortunately I have to use the existing GET call.

I am going to loop the array and make a call for each number which I have in the multiple number list.

I want to know what is the best way to make a call for each number and as soon as result for one number is available update the UI instead of waiting for all calls to finish?

here is my GET call

searchNumbers(
    Request: string, type: string) {
    const requestOptions = {
      headers: this.headers
    };
    const url = `${environment.customerApiUrl.status}?${type.toLowerCase()}=${Request}`;  
    return this.httpClient.get(
        url, requestOptions );
  }

What is the best way to call this endpoint Asynchronously and updated the UI as soon as I receive the data for any particular number from the number list.

Upvotes: 1

Views: 1482

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

To accomplish this, you can use from to create an observable stream that emits each array element individually. Then use mergeMap to map each value to your api call (that returns observable) and merge their output into the created stream:

  searchMultipleNumbers(numbers: number[]) {
    return from(numbers).pipe(
      mergeMap(id => this.httpClient.get(`url/${id}`))
    );
  }

The output responses from the calls will be emitted individually as they come back.

Here's a working StackBlitz.

If you wanted to emit the full array off all results each time a response comes back, you could use scan to emit an array of all emissions.

  searchMultipleNumbers(numbers: number[]) {
    return from(numbers).pipe(
      mergeMap(id => this.httpClient.get(`url/${id}`)),
      scan((all, val) => [...all, val], [])
    );
  }

(StackBlitz #2)

To catch and ignore Errors, you can use catchError and just return EMPTY:

  searchMultipleNumbers(numbers: number[]) {
    return from(numbers).pipe(
      mergeMap(id => this.httpClient.get(`url/${id}`).pipe(catchError(()=>EMPTY))
    );
  }

Upvotes: 1

Related Questions