Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Make multiple HTTP calls sequentially

I need to make a function to make HTTP calls sequentially inorder to use response of one call into other one like getting IP address of user from first call and use that IP to register user in second call.

Demo code:

registerUser(user: User) {     this.utility.getIpAddress()     .subscribe(data => {         this.ipAddress = data.ip;     });     const body = {         UserName: user.UserName,         Email: user.Email,         //...         UserIP: this.ipAddress,     }     return this.http.post(this.registerAPI, body); } 
like image 684
Abdul Rafay Avatar asked Jul 06 '18 14:07

Abdul Rafay


People also ask

What is ForkJoin in Angular?

ForkJoin. This operator is best used when you have a group of observables and only care about the final emitted value of each. It means that forkJoin allows us to group multiple observables and execute them in parallel, then return only one observable.

How do I use ForkJoin in angular 8?

There are a few steps to accomplish this tutorial:Install Angular CLI and Create Angular 8 Application. Create an Angular 8 Service. Display Multiple Details of Data using Angular 8 Material. Run and Test the Complete Angular 8 RxJS Example.


1 Answers

This can be achieved using the switchMap operator. This example uses RxJS 5.5+ pipeable operators.

import { switchMap } from 'rxjs/operators';  registerUser(user: User) {   return this.utility.getIpAddress().pipe(     switchMap(data => {       this.ipAddress = data.ip;        const body = {         UserName: user.UserName,         Email: user.Email,         UserIP: this.ipAddress,       };        return this.http.post(this.registerAPI, body);     })   ) } 

RxJS < 5.5:

import { switchMap } from 'rxjs/operators';  registerUser(user: User) {   return this.utility.getIpAddress()     .switchMap(data => {       this.ipAddress = data.ip;        const body = {         UserName: user.UserName,         Email: user.Email,         UserIP: this.ipAddress,       };        return this.http.post(this.registerAPI, body);     }); } 
like image 181
Alexander Staroselsky Avatar answered Sep 24 '22 15:09

Alexander Staroselsky