Global Data Sharing in Angular 4

In Angular 2/4 sharing data from one component to another forms an important aspect of the Angular application

Angular allows us many ways in which we can achieve this data sharing functionality either by using Services or any other external javascript libraries.

For this demonstration we will use Services to share data globally in our application between different modules and their components.

Download Source Code for this Lab

Source Code

Contents

What is a Service?

What is a Dependency Injection?

How do we share our data Globally in Angular?

Demonstration of Global Data Sharing

What is a Service?

A service is basically a typescript function which can perform a single functionality.

It is a functionality which needs to implement commonly in across multiple modules so basically making it reusable code which reduces code duplicity.

Services can be best used to create, update and delete data in angular.

One of main purpose of using services in angular is enforce separation of concerns.

What is a Dependency Injection?

Dependency Injection gives us the ability to add functionalities across different components at runtime in an angular application.

We can create a service by importing Injectable library from our @angular/core.

import { 
   Injectable 
} from '@angular/core'; 

@Injectable () 
export class Service {  
   commonFunction(): string { 
      return "Hello world"; 
   } 
}

In angular application we need to give references inside the provider.

Provider in angular is a pre-defined object that gives instructions to the injector in our application on how to create those dependencies.

Most dependencies are services in angular hence angular uses DI to provide components the individual services they need for functionality.

How do we share our data Globally in Angular?

To share data globally across multiple modules we cannot declare our service in each and every module individually.

If we can inject a service into a parent module and it will be included inside all the child modules.

Demonstration of Global Data Sharing

In the following we have an angular 4 application where we have two countries with same currency but the components for this these two country lie in two different modules in our angular application complete with their complete separate routings and views.

So we cannot have our service inside these individual modules as their scope will be limited to those modules.

Hence we need to inject our service into a module which lies in higher in the general hierarchy and then referencing it our individual components of our two countries.

Hence we need to create a service and refer it our app.module.ts which is our outermost module in this current application.

Let us name our service global.service.ts for sake of simplicity.

Our project structure should look something like this

We will define proper references for the both our submodules inside our app-routing.constant.ts .

You can find all the necessary code used in this application included inside the source which will be linked in this article.

All the while let’s include the following code inside our app.module.ts

import { GlobalCurrencyService } from './global.service';
providers: [GlobalCurrencyService],

In our service global.service.ts let’s just define a simple code to just set and get a currency.

import { Injectable, Directive } from '@angular/core';
@Injectable()
export class GlobalCurrencyService {
    private currency;
    constructor() { }
    setCurrency(val) {
        this.currency = val;
    }
    getCurrency() {
        return this.currency;
    }
}

Now let’s write the a simple set and get code inside our global.service.ts

import { Injectable, Directive } from '@angular/core';

@Injectable()
export class GlobalCurrencyService {
    private currency: string;
  
    constructor() { }

    setCurrency(val) {
        this.currency = val;
    }

    getCurrency() {
        return this.currency;
    }
  }

After this let us include the reference for this services in both our components which are included in different modules and their respective views.

For ind.component.ts:

import { Component, Injectable, Directive } from '@angular/core'
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/Rx';
import { GlobalCurrencyService } from '../../global.service';


@Component({
    selector: 'app-root',
    templateUrl: "/INDView/IND"

})
@Injectable()

export class INDCurrencyComponent {
    private indCurrency: string = null;
    private itemList: any;
    constructor(private currencyService: GlobalCurrencyService) {
        this.indCurrency = this.currencyService.getCurrency();
        this.itemList = this.currencyService.getList();
    }

    SetGlobalData() {
        this.currencyService.setCurrency(this.indCurrency);
    }
    Save() {
        this.itemList.push({ "item": this.indCurrency });
        this.currencyService.setList(this.itemList);
    }
}

For views:

<label>
    <input type="text" [(ngModel)]="indianCurrency" value="" (ngModelChange)="SetGlobalData()" />
    <input type="button" value="Save" (click)="Save()" />
</label>
{{val}}

For np.component.ts:

import { Component, Injectable, Directive } from '@angular/core'
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/Rx';
import { GlobalCurrencyService } from '../../global.service';


@Component({
    selector: 'app-root',
    templateUrl: "/NPView/NP"

})
@Injectable()

export class NPCurrencyComponent {
    private nepaliCurrency: string = null;
    private itemList: Array = new Array();
    constructor(private currencyService: GlobalCurrencyService) {
        this.nepaliCurrency = this.currencyService.getCurrency();
        this.itemList = this.currencyService.getList();
    }
    SetGlobalData() {
        this.currencyService.setCurrency(this.nepaliCurrency);
    }
    Save() {
        this.itemList.push(this.nepaliCurrency);
        this.currencyService.setList(this.itemList);
   
    }
}

For views:

<label>
    <input type="text" [(ngModel)]="nepaliCurrency" value="" (ngModelChange)="SetGlobalData()"  />
    <input type="button" value="Save" (click)="Save()" />
</label>
{{val}}

As we see in the demo when we pass our currency in our input field in the Indian component.

Then switch to Nepal Component in our navigation which is in a different component which belongs to a different module.

Hence the data can be shared globally by including it in the outermost module in angular.

Like the above example which we have purposely kept simple we can pass list and other values to our Services and retrieve it in any other sibling module which is content under a parent module where we will reference our service.

Download Source Code For This Lab

Source Code

+91-022-49786776
+91 9967590707
questpond@questpond.com / questpond@gmail.com