0

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

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.

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! Thank you @MoxxiManagarm. I was missing that merge thing via spread operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.