Search code examples
angularrxjsangular14rxjs7

Angular: http RxJS dependant http requests


I am developing a small app with Angular 14.1. I need to create a service that get information from N endpoint and is dependant of an endpoint. I need a solution that could retrieve previous information fast as possible. This data will be consumed by a component.

Extended information:

Current service is required to request information from HTTP endpoint that return some data like this:

{
  "name": "test",
  "documents":[
    {
      "id": 1,
      "name": "document 1",
      "type": "a"
    }, {
      "id": 2,
      "name": "document 2"
      "type": "b"
    },
    {
      "id": 3,
      "name": "document 3"
      "type": "a"
    }
  ]
}

With previous response:

  1. I need to filter all documents that their type are "a"

  2. I need for each "id" create a new HTTP request to another endpoint to get more information. Return some data like this:

    {
        "name": "document 1",
        "type": "a",
        "start": "2022-10-10"
    }
    
  3. I need to get a class instance for previous data.

I tried different ways that I think that are too dirty. Could you help me?

Thanks!


Solution

  • That's just a combination of concatMap and a forkJoin() that will make all the inner requests concurrently:

    getDocuments()
      .pipe(
        concatMap(response => {
          const documents = response.documents.filter(doc => doc.type === 'a');
          return forkJoin(documents.map(doc => otherRequest(doc)));  
        },
      )