The concatMap operator will not subscribe to the next Observable until the current one is completed. It will maintain the order in which the Observable are emitted.
In this example, we shall see how to call multiple api one after the other using the concatMap operator.
Lets create an angular application using the angular cli command.
ng new concat-tutorial
Lets create a service to make http api call. Enter the following angular cli command to create a service.
ng g s services/http
Now open the file and modify the code as below.
Now create a service using the below angular cli command.
ng g s services/rxjs
This will create us a service in the services folder. Now open the rxjs.service.ts file and add the following code.
Here we have create a variable domainUrl to hold base url and reqArrayvariable to hold the array of integers to make api call by appending to the above url.
We create a function with the name concatMapCall and inside the function we use the from rxjs operator which is used to convert an array to an observable. Here we give the reqArray array variable as parameter to the from operator, which will be piped and given to the concatMap operator one after the other.
The concatMap operator gets the integers in the array one by one in the 'id' parameter and appends the 'id' to the domainUrl and makes an api call. Here the concatMap will wait until the current Observable is completed. Only then it will form the next url and make the api call. So here it makes 5 api calls one after the other.
Now lets call the concatMapCall function in the RxjsService service in the app.component.ts. Open the app.component.ts file and modify the code as below.
Run the application using
ng serve --o
Now press F12 and check the Console and Network tab. It looks as below.

Comments
Post a Comment