Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concat multilevel API calls in Angular using rxjs

I am new to rxjs I am calling three api calls using the hacker new api. I want to concat response of the last api call to the second api call.

I want to achieve something like this.

[
    {
        "by": "john"
        "title": "Sample title"
        "time":1657786985
        "karma": 123456 // this is from the third api call that i want to merge
    },
    {
        "by": "jane"
        "title": "Sample title 2"
        "time":1657786333
        "karma": 123456 // this is from the third api call that i want to merge
    }
]

So far this is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.service.fetchStories().pipe( // get list of id array
      switchMap(idArray => forkJoin(
        idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
          concatMap(itm => this.service.fetchUserById(itm.by)) // second api call i want to merge { karma } to the first api call
        )))
      ),
      take(1)
    ).subscribe(data => console.log(data));

But the result is I am getting only the response of the last api call. Can somebody help me. I am trying to learn rxjs.

>Solution :

All you need to do is to pipe the third call again and merge the results.

this.service.fetchStories().pipe( // get list of id array
      switchMap(idArray => forkJoin(
        idArray.map(id => this.service.fetchStoryItems(id).pipe( // first api call
          concatMap(itm => this.service.fetchUserById(itm.by).pipe(map(({karma}) => ({ ...itm, karma }))))
        )))
      ),
      take(1)
    ).subscribe(data => console.log(data));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading