I need to make chained http calls to api. In first response I get observable, then I use map operator and return this result:
getAreaByKey(key: string): Observable<Area> {
return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
map(result => {
return {
'key': result['Key'],
'name': result['Description'],
'experts': result['Experts']
};
})
);
}
Then I need to make another http call with parameter result['Experts'] , which is array with ID's. How can I pass that parameter to next call? I've tried to use SwitchMap, but there is no result. And how to save response data from this calls? because I need to use both in my template.
switchMap
is the right operator to use to chain http calls. Whenever the first observable emits, you can create a second observable using the value emitted.
In your example:
getAreaByKey(key: string): Observable<Area> {
return this.http.get<any[]>(`${this.api}/areas/${key}`).pipe(
map(result => {
return {
'key': result['Key'],
'name': result['Description'],
'experts': result['Experts']
};
}),
tap(res1 => // save the first response here),
switchMap(res1 => this.anotherHttpCall(res.experts)),
tap(res2 => // save the second response here)
);
}
As for saving the data, you can either do this in a tap after each observable as above, or you can use async | pipe
async | pipe
in the template.
If there is no result, it might be that you are not subscribing to the observable:
const obs$ = this.getAreaByKey(); // the observable is defined but the http call has not been made
obs$.subscribe(); // http call is triggered
Again, you can do this manually as above or use async | pipe
async | pipe
in the template.
Check out https://angular.io/guide/observables
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
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.