et3rnal
et3rnal

Reputation: 342

Multiple http request in the background using angular 6

I have to fetch data on small batches to complete the data I already have in the frontend, So let say I have hundreds of objects of an id, name and the other fields are empty as I have to get them from another endpoint on by passing the id, however, this other endpoint is quite slow and I need to do this process for let say 5 at the time and in the background "without interrupting any other requests".

What is the best approach to do that? and append the fetched data to its corresponding item inside the list of objects?

Upvotes: 0

Views: 1753

Answers (2)

Picci
Picci

Reputation: 17762

If I understand right, you start with an array of objects of which you know id and name. You need to populate all these objects with additional data which you can fetch using a slow API, and therefore you do not want to have more than 5 of such requests flying at a time.

Let's assume that the invocation of such API is implemented via the method getDataForId(id) and that the populate of the object with the additional data retrieved from the API is performed by the method populate(obj, data) where obj is the object that has to be populated and data is the raw data to be used to populate the object.

If this is all right, you can consider an approach along these lines

const objArray = [
  {id: 123, name: 'first'},
  {id: 456, name: 'second'},
  ......
  {id: xyz, name: 'last'},
];

    from(objArray).pipe(
       mergeMap(
          obj => getDataForId(objArray.id).pipe(
             map(data => populate(obj, data))
          ), 5
       )
    )
    .subscribe()

ALTERNATIVE IMPLEMENTATION - after the comment

You can consider also to fetch the list from the back end and then get the items in chunks of 5 with full details. You can achieve this with code which would look like

getListOfIds().pipe(
   bufferCount(5),
   map(arrayOf5Ids => getDataForId(objArray.id).pipe(
             map(data => populate(obj, data))
   )),
   switchMap(arrayOf5Observables => forkJoin(arrayOfObservables)),
)
.subscribe(arrayOf5Items => // do what you want}

Upvotes: 1

Chunbin Li
Chunbin Li

Reputation: 2244

you can use mergeMap , like this

  this.http.get('/api1').pipe(
      mergeMap(character => this.http.get('/api2'))
    ).subscribe(() => {
       ....  
    });

References - Angular Multiple HTTP Requests with RxJS

Upvotes: 1

Related Questions