Fork joins in angular
Fork joins in angular are used to help to handle the concurrent request. Sometimes various data is gathered from multiple sources in a single request and data must be displayed only when complete data successfully arrives on the webpage from all sources. Partial data must be discarded. Observables provide a method called forkJoin() to “wrap” multiple Observables, and make multiple concurrent http.get() requests. the operation will be failed if all requests are not completed. Subscriber method work as a handler for all observables.
In this example, customers.json and employees.json are two data sourced which will be read in a single request.
Step 1: Create two new files customers.json and employees.json and put into assets folder.
[ {"fname":"Jane","lname":"Jones","city":"San Francisco"}, {"fname":"John","lname":"Smith","city":"New York"}, {"fname":"Dave","lname":"Stone","city":"Seattle"}, {"fname":"Sara","lname":"Edson","city":"Chicago"} ]
[ {"fname":"Paolo","lname":"Friulano","city":"Maniago"}, {"fname":"Luigi","lname":"Napoli","city":"Vicenza"}, {"fname":"Miko","lname":"Tanaka","city":"Yokohama"}, {"fname":"Yumi","lname":"Fujimoto","city":"Tokyo"} ]
Step 2: Create new service myservice
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Rx'; @Injectable() export class MyserviceService { constructor(private http : Http) { } getemployees() { return this.http.get('employees.json').map((res: Response) => res.json()); } gettwodata() { return Observable.forkJoin(this.http.get('assets/employees.json').map((res: Response) => res.json()), this.http.get('assets/customers.json').map((res: Response) => res.json())); } }
two arrays with employee and customer data will be returned by gettwodata service method.
Step 3: Create new component forkjoinex
import { Component, OnInit } from '@angular/core'; import { MyserviceService } from '../myservice.service'; @Component({ selector: 'app-forkjoinex', templateUrl: './forkjoinex.component.html', styleUrls: ['./forkjoinex.component.css'], providers:[MyserviceService] }) export class ForkjoinexComponent implements OnInit { public employee; public customer; constructor(private ser : MyserviceService) { } ngOnInit() { this.getdata(); } getdata() { this.ser.gettwodata().subscribe(data => { this.employee = data[0] this.customer = data[1] }); } }
<p> forkjoinex works! </p> <ul> <li *ngFor="let e of employee"> {{ e.fname }} {{ e.lname }} lives in {{ e.city }} </li> </ul> <ul> <li *ngFor="let c of customer"> {{ c.fname }} {{ c.lname }} lives in {{ c.city }} </li> </ul>
Step 4: Pass reference into app.component.html
<app-forkjoinex></app-forkjoinex>
Step 5: Pass reference of newly created service into app.module.ts then run program
ng serve –open