I need to make first HTTP request and get from response array of object. Then I need to make HTTP request for every object in array (probably in loop) to get extra info. All this inside Angular. I try with pipes but have some difficulties.
-
3What "difficulties"? Give a minimal reproducible example.jonrsharpe– jonrsharpe2019-05-28 07:40:41 +00:00Commented May 28, 2019 at 7:40
-
I was able to build this:this.homeworld = this.http.get('/api/people/1').pipe( mergeMap(character => this.http.get(character.homeworld)) ); from this: this.http.get('/api/people/1').subscribe(character => { this.http.get(character.homeworld).subscribe(homeworld => { character.homeworld = homeworld; this.loadedCharacter = character; }); });Darien Fawkes– Darien Fawkes2019-05-28 07:44:47 +00:00Commented May 28, 2019 at 7:44
-
2Edit the question. That doesn't seem to do anything with arrays.jonrsharpe– jonrsharpe2019-05-28 07:45:12 +00:00Commented May 28, 2019 at 7:45
2 Answers
Basically you would use a mergeMap/flatMap for a nested api call by pulling the value out of the inner Observable and passing it back to the parent stream.
Like in the example in below answer if you had to make a nested call for fetching a User and then his preferences, you would use flatmap like below.
ngOnInit() {
this.userService.getUser().pipe(
tap(u => this.user = u),
flatMap(u => this.userService.getPreferences(u.username))
).subscribe(p => this.preferences = p);
}
Comments
Your explanation is quite vague, and without a pseudocode example or an actual example of what you've tried to do, this is hard to answer.
But what I gather is that you need:
API call 1:
{ ids: [1, 2, 3] }
API call 2 takes an ID (api(1), api(2), api(3) etc.) and returns:
{ something: 'else', id: 1 }
In RxJS you would want to switchMap for every ID you get, so you can switch the subscription to a new Observable. If you want all of these to come in when they come in you would merge these. If you want them to come in predictably and in order you would concat them.
Basic example:
this.http.get<{id: number[]}>('api1').pipe(
switchMap(ids => {
return concat(ids.forEach(id => {
return this.http.get<{ something: string, id: number}>('api2/' + id)
})
}).subscribe(console.log)