简体   繁体   中英

Multiple HTTP calls using RXJS inside of pipe operator

I have 3 API endpoints (candidates, vacancies and interviews).

{
    "candidates": [
        {
           "id": 1,
           "name": "Serj"
        },
        {
           "id": 2,
           "name": "Alex"
        },
      ],
    "vacancies": [
        {
           "id": 1,
           "title": "Java"
        },
        {
           "id": 2,
           "title": "JS"
        },
      ],
   "interviews": [
        {
           "id": 1,
           "candidateId": 1,
           "vacancyId": 2,
           "date": "2018-12-11"
        },
        {
           "id": 2,
           "candidateId": 2,
           "vacancyId": 1,
           "date": "2018-12-11"
        },
      ]
}

First of I get interviews by date and and have an array of interviews.

const params = new HttpParams().set('date', '2018-12-11');
this.http.get('http://localhost:3000/interviews', {params}).pipe();

And as I subscribe() to the output of the pipe() - I wanna get array of interviews where instead of "candidateId" and "vacancyId" are actual objects candidate and vacancy fetched from appropriate endpoints.

So result ( Interview[] ) should look like:

[
  {
    "id": 1,
    "candidate": {
      "id": 1,
      "name": "Serj"
    },
    "vacancy": {
      // vacancy instance
    },
    "date": "2018-12-11"
  },
  // second interview object
]

Thanks for any help!

If I understood it right, you want your interview response to be filtered out to contain an array of objects with fields candidateId and vacancyId only ?

If that would be the case, you can use this method:

this.http.get('http://localhost:3000/interviews', {params})
  .pipe(
     flatMap(item => item),
     map(({ candidates, vacancies, interviews}) => 
        interviews.map(({ id, candidateId, vacancyId, date }) => ({ 
           id,
           candidate: candidates.filter(c => c.id === candidateId)[0], 
           vacancy: vacancies.filter(v => v.id === vacancyId)[0],
           date
        })
     )),
     reduce((acc, val) => [acc, val])  
  )
  .subscribe(response => console.log(response));

Had created a Stackblitz Demo for your reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM