angular 5 forkjoin example | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

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"},

Step 2: Create new service myservice

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

export class MyserviceService {

  constructor(private http : Http) {

     return this.http.get('employees.json').map((res: Response) => res.json());
     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';

  selector: 'app-forkjoinex',
  templateUrl: './forkjoinex.component.html',
  styleUrls: ['./forkjoinex.component.css'],
export class ForkjoinexComponent implements OnInit {

  public employee;
  public customer;
  constructor(private ser : MyserviceService) { }

  ngOnInit() {
this.ser.gettwodata().subscribe(data => { 
  this.employee = data[0]
  this.customer = data[1]

  forkjoinex works!
  <li *ngFor="let e of employee">
    {{ e.fname }} {{ e.lname }} lives in {{ e.city }}
  <li *ngFor="let c of customer">
    {{ c.fname }} {{ c.lname }} lives in {{ c.city }}

Step 4: Pass reference into app.component.html


Step 5: Pass reference of newly created service into app.module.ts then run program

ng serve –open

forkjoin in angular 5 example

forkjoin in angular 5 example