SoFunction
Updated on 2025-04-13

angular.js4 uses RxJS to handle multiple Http requests

Sometimes when entering a certain page, we need to get data from multiple API addresses and then display it. Managing multiple asynchronous data requests can be difficult, but we can use the functions provided by the Angular Http service and the RxJS library to achieve the above functions. There are multiple ways to process multiple requests, using serial or parallel methods.

Basic knowledge

mergeMap

The mergeMap operator is used to get the value from the internal Observable object and then return it to the parent stream object.

Merge Observable objects

const source = ('Hello');
//map to inner observable and flatten
const example = (val => (`${val} World!`));

const subscribe = (val => (val)); //output: 'Hello World!'

In the above example, there are two Observable types:

  • Source Observable object - i.e. source object
  • Internal Observable object - i.e. (`${val} World!`) object

The value output from the source Observable object is merged only when the internal Observable object emits a value, and the combined value is finally output.

forkJoin

forkJoin is Rx version (), which means that the value will be returned at one time after all Observables are completed.

Merge multiple Observable objects

const getPostOne$ = (1000).mapTo({id: 1});
const getPostTwo$ = (2000).mapTo({id: 2});

(getPostOne$, getPostTwo$).subscribe(
 res => (res) // [{id: 1}, {id: 2}]
); 

Processing Http requests

Let's first take a look at a simple example of Angular Http service.

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

import 'rxjs/add/operator/map';

@Component({
 selector: 'app-root',
 template: `
  <p>HttpModule Demo</p>
 `
})
export class AppComponent implements OnInit {
 constructor(private http: Http) { }

 ngOnInit() {
  ('/users')
   .map(res => ())
   .subscribe(users => (users));
 }
}

In the above example, we inject the http service through dependency injection, and then call the get() method of the http object in the ngOnInit() method to get the data. This example is very simple. It only processes one request. Next, let’s take a look at how to handle two requests.

Map and Subscribe

Sometimes, when we send the next request, we need to rely on the data from the previous request. That is, we get the corresponding data in the callback function that needs to be in the previous request, and then initiate another HTTP request.

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
 selector: 'app-root',
 template: `
  <p>{{username}} Detail Info</p>
  {{user | json}}
 `
})
export class AppComponent implements OnInit {
 constructor(private http: Http) { }

 apiUrl = '/users';
 username: string = '';
 user: any;

 ngOnInit() {
  ()
   .map(res => ())
   .subscribe(users => {
    let username = users[6].username;
    (`${}?username=${username}`)
     .map(res => ())
     .subscribe(
      user => {
        = username;
        = user;
      });
   });
 }
}

In the above example, we first get all users' information from the /users address, and then further get the user's detailed information based on the username of the specified user. Although the function has been implemented, is there any better solution? The answer is yes, and the above process can be optimized through the mergeMap operator provided in the RxJS library.

mergeMap

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';

@Component({
 selector: 'app-root',
 template: `
  <p>{{username}} Detail Info</p>
  {{user | json}}
 `
})
export class AppComponent implements OnInit {
 constructor(private http: Http) { }

 apiUrl = '/users';

 username: string = '';

 user: any;

 ngOnInit() {
  ()
   .map(res => ())
   .mergeMap(users => {
     = users[6].username;
    return (`${}?username=${}`)
     .map(res => ())
   })
   .subscribe(user =>  = user);
 }
}

In the above example, we solved the problem of nested subscriptions through the mergeMap operator. Finally, let’s take a look at how to handle multiple parallel Http requests.

forkJoin

In the next example, we will use the forkJoin operator. If you are familiar with Promises, this operator is similar to the functions implemented by (). The forkJoin operator receives a list of Observable objects and executes them in parallel. Once the Observable objects in the list emit values, the Observable object returned by the forkJoin operator emits a new value, that is, a list of output values ​​of all Observable objects. Specific examples are as follows:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';

@Component({
 selector: 'app-root',
 template: `
  <p>Post Detail Info</p>
  <ul>
   <li>{{post1 | json}}</li>
   <li>{{post2 | json}}</li>
  </ul>
 `
})
export class AppComponent implements OnInit {
 constructor(private http: Http) { }

 apiUrl = '/posts';

 post1: any;

 post2: any;

 ngOnInit() {
  let post1 = (`${}/1`);
  let post2 = (`${}/2`);

  ([post1, post2])
   .subscribe(results => {
    this.post1 = results[0];
    this.post2 = results[1];
   });
 }
}

I have something to say

Besides mergeMap, what is the use of switchMap in RxJS?

The switchMap operator is used to map the values ​​emitted by the source Observable object. If a new Observable object appears, the previous unprocessed Observable object will be unsubscribed after the new Observable object emits a new value.

Example of usage:

var source = (, 'click');
var example = (e => (100).take(3));

({
  next: (value) => { (value); },
  error: (err) => { ('Error: ' + err); },
  complete: () => { ('complete'); }
});

Example marble diagram:

source : -----------c--c-----------------...
    concatMap(c => (100).take(3))
example: -------------0--0-1-2-----------...

After the above code is run, the output result of the console:

0
0
1
2

In the scenario where Http service is actually used, such as implementing the AutoComplete function, we can use the switchMap operator to cancel useless Http requests.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.