Demonstration of Parallel Service Execution in Angular 2

Rajnilari2015
Posted by in Angular 2 category on for Beginner level | Points: 250 | Views : 663 red flag

AngularJS 2 is an open source, MV* Javascript framework developed by Google. It is widely use across the industry to build web applications. In this article, we will demonstrate how to execute services in parallel in Angular 2.


 Download source code for Demonstration of Parallel Service Execution in Angular 2

Introduction

AngularJS 2 is an open source, MV* JavaScript framework developed by Google. It is widely use across the industry to build web applications. In this article, we will demonstrate how to execute services in parallel in Angular 2.

Using the code

Open app.ts file inside the src folder and write the below code

//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { 
  HttpModule 
  Http, 
  Response
} from '@angular/http';

import {Observable} from 'rxjs/Rx'; // Include all operators and import the Observable class


// Annotation section
@Component({
  selector: 'my-app',
  template: `
    <div style="width: 100%; margin: 0 auto;">     
      <user-selector></user-selector>
    </div>
  `,  
})
// Component controller
export class App { 
  constructor() { }
}

// Annotation section
@Component({
  selector: 'user-selector',
  templateUrl: 'user-information-apps.html'
})

// Component controller
export class UserInformation {

  users1:Observable<Array<any>>;
  users2:Observable<Array<any>>;
  users3:Observable<Array<any>>;
  users4:Observable<Array<any>>;

  url: string;

  constructor(private _http: Http) {  
    this.url='http://jsonplaceholder.typicode.com/posts';
  } //end constructor 

  getUserDetailsInParallel(){ 

  Observable.forkJoin(
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json())
    ).subscribe(
      data => {      
        this.users1 = data[0].slice(0, 2)
        this.users2 = data[1].slice(2, 4)
        this.users3 = data[2].slice(4, 6)
        this.users4 = data[3].slice(6, 8)
      },
      err => console.error(err)
    );
  
    } //end getUserDetails
} //end UserInformation class
  


@NgModule({
  imports: [ 
    BrowserModule, 
    HttpModule 
  ],
  declarations: [ App,UserInformation ],
  bootstrap: [ App ]
})
export class AppModule {}

Angular 2 provided the forkJoin method of Observable class.We include it as under

import {Observable} from 'rxjs/Rx';

RxJs stands for Reactive Extensions for JavaScript. It's an implementation of Observables for JavaScript. Observable is the async pattern used in Angular 2. It notifies the subscribers/observers when some changes happens. It follows the observer design pattern.

In order to enable Http in the application, we need to import the below modules from the @angular/http module

import { 
  HttpModule 
  Http, 
  Response
} from '@angular/http';

At first we have defined four array properties of type Observable in the class UserInformation

users1:Observable<Array<any>>;
users2:Observable<Array<any>>;
users3:Observable<Array<any>>;
users4:Observable<Array<any>>;

In the constructor of the UserInformation class, we have injected HTTP Dependency Injection.

 constructor(private _http: Http) {  
    this.url='http://jsonplaceholder.typicode.com/posts';
  } //end constructor 

Next we have invoked the services in parallel from getUserDetailsInParallel() method

getUserDetailsInParallel(){ 

  Observable.forkJoin(
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json()),
        this._http.get(this.url).map((res:Response) => res.json())
    ).subscribe(
      data => {      
        this.users1 = data[0].slice(0, 2)
        this.users2 = data[1].slice(2, 4)
        this.users3 = data[2].slice(4, 6)
        this.users4 = data[3].slice(6, 8)
      },
      err => console.error(err)
    );
  
    } //end getUserDetails

Let us imagine that we have many master records which are independent of each other or some services which can be loaded in parallel. For this to happen we will execute a set of requests, but we want to wait for all to be finished. Observables of Angular 2 provides the forkJoin method for this. This method is similar to promises in Angular 1.x.

The Map operator creates a new array with the results of calling a function for every array element.

The subscribe() method observes the output return by _http.get() method. For parsing the response as JSON, we use res.json().The slice() method returns the selected elements in an array as a new array object. And finally we are assigning the array elements to the various properties defined.

Now we need to bind the data to the view. So let's create the below user-information-apps.html

<h1>
  <b>
    <font color="blue">User Information In Parallel</font>
  </b>
</h1>

  <table>
    <tr>
      <td>

        <fieldset>
            <legend>Data From Service 1</legend>
                 <table border="1">
                <tr>
                    <th style="background-color: #4CAF50;">Id</th>
                    <th style="background-color: #4CAF50;">User Id</th>            
                    <th style="background-color: #4CAF50;">Title</th>
                    <th style="background-color: #4CAF50;">Body</th>
                </tr>

                <tr *ngFor="let u of users1">
                      
                    <td><span>{{u.id}}</span></td>
                    <td><span>{{u.userId}}</span></td>               
                    <td><span>{{u.title}}</span></td>
                    <td><span>{{u.body}}</span></td>

                </tr>       
              </table>
        </fieldset>
      </td>
      <td>

        <fieldset>
            <legend>Data From Service 2</legend>
                 <table border="1">
                <tr>
                    <th style="background-color: #DEB887;">Id</th>
                    <th style="background-color: #DEB887;">User Id</th>            
                    <th style="background-color: #DEB887;">Title</th>
                    <th style="background-color: #DEB887;">Body</th>
                </tr>

                <tr *ngFor="let u of users2">
                      
                    <td><span>{{u.id}}</span></td>
                    <td><span>{{u.userId}}</span></td>               
                    <td><span>{{u.title}}</span></td>
                    <td><span>{{u.body}}</span></td>

                </tr>       
              </table>
        </fieldset>
      </td>

      <td>
        <fieldset>
            <legend>Data From Service 3</legend>
                 <table border="1">
                <tr>
                    <th style="background-color: #006400;">Id</th>
                    <th style="background-color: #006400;">User Id</th>            
                    <th style="background-color: #006400;">Title</th>
                    <th style="background-color: #006400;">Body</th>
                </tr>

                <tr *ngFor="let u of users3">
                      
                    <td><span>{{u.id}}</span></td>
                    <td><span>{{u.userId}}</span></td>               
                    <td><span>{{u.title}}</span></td>
                    <td><span>{{u.body}}</span></td>

                </tr>       
              </table>
        </fieldset>
      </td>
      <td>

        <fieldset>
            <legend>Data From Service 4</legend>
                 <table border="1">
                <tr>
                    <th style="background-color: #1E90FF;">Id</th>
                    <th style="background-color: #1E90FF;">User Id</th>            
                    <th style="background-color: #1E90FF;">Title</th>
                    <th style="background-color: #1E90FF;">Body</th>
                </tr>

                <tr *ngFor="let u of users4">
                      
                    <td><span>{{u.id}}</span></td>
                    <td><span>{{u.userId}}</span></td>               
                    <td><span>{{u.title}}</span></td>
                    <td><span>{{u.body}}</span></td>

                </tr>       
              </table>
        </fieldset>
      </td>
    </tr>    

    <div>
      <button (click)="getUserDetailsInParallel()" id="btnUserDetailsInParallel">Invoke Parallel service for User Details</button>
    </div>

Here we have declared four tables, each responsible for displaying it's own record.The let keyword of Type Script (and ES6) allows to define variables with true block scope. ngFor of Angular 2 is the replacement for ng-repeat of AngularJS 1.x. This directive instantiates a template once per item from an iterable. The *is a shorthand for using the new Angular 2 template syntax with the template tag. It is the syntactic sugar that brings the structural Directive of Angular 2.

Now open the index.html in Fire Fox

Click on the "Invoke Parallel service for User Details" button and the result is as under.

References

ANGULAR 2 SERVICES

Conclusion

In this article we have learnt how to execute services in parallel in Angular 2. This will help in faster page performance. Hope this will be helpful. Thanks for reading. Zipped file is attached herewith.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)