Solution 2 – Permanent Data Sharing

 
A previous example is not viable if we want to permanently store our data while an application is up and running.
 
For that we will need to use a service. Here’s how it looks like in this example:
 
import { Injectable } from '@angular/core';

@Injectable()
export class ShareService {
	
    firstName: string;
    lastName: string;

    constructor() {
        this.firstName = 'Blank';
        this.lastName = 'Name';
    }
 
    setUserName(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;       
    }
 
    getUserName() {
        return this.firstName + ' ' + this.lastName;
    }  
}
 
One warning before you go this way; you need to be very careful. If you include this service using the providers keyword on a page level, each page will have a separate instance which brakes the point of data sharing.
 
Instead, initialize this sharing service on a core parent application level, to be more specific, here: app.module.ts
 
This is how we’re going to initialize it:
 
import { ShareService } from '../services/share/share';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage,
    SecondPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    SecondPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    ShareService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
 
providers keyword is the most important line here, this solution will not work if this service is not included in this segment.
 
We can now use ShareService to store application data:
 
constructor(shareService: ShareService) {
 
shareService.setUserName('John','Johnson');
 
The code is almost the same on the destination page. There’s only one difference, do not use providers keyword inside a @Component decorator. You will not cause an error, but this approach will create another ShareService instance, which will not hold our data.
 
The first thing we need to do is import ShareService:
 
import { ShareService } from '../../services/share/share';
 
Inject it:
 
constructor(public navCtrl: NavController, public navParams: NavParams, shareService: ShareService, public events: Events) {
 
Finally, query our stored data:
 
this.serviceData = shareService.getUserName();
 
 
 

Solution 3 – Using Event emitter

 
First include Event emitter into any page where you want to use it:
 
import { Events } from 'ionic-angular';
 
To be able to receive this data we first need to publish it:
 
let dummy = {
	firstName: "Jack",
	lastName: "Bauer"
}

events.publish("shareObject", dummy, 2);
 
The first parameter is always a publish name, you can use any string you want. The second one and every other parameter are objects you want to publish (one or more objects).
 
Of course, just like I told you in the beginning of this article, only loaded pages will be able to subscribe (get) these data. That’s the reason, why, in my example, I’m sending data backward, from the second page to the home page.
 
This is how you can receive these data:
 
events.subscribe('shareObject', (dummy, dummyNumber) => {
	console.log('Welcome', dummy.firstName, 'at', dummyNumber);
});	
 
 
 

Source Code

 
In case GitHub repo is not available and you can only use code provided below, this is what project folder looks like (image was taken from Sublime text editor):
 
Ionic 2 Data Share Folder Structure
 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { SecondPage } from '../pages/second/second';
import { ShareService } from '../services/share/share';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    SecondPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    SecondPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    ShareService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}
 
home.ts
import { Component } from '@angular/core';
import { NavController, Events } from 'ionic-angular';
import { SecondPage } from '../second/second';
import { ShareService } from '../../services/share/share';

@Component({
	selector: 'page-home',
	templateUrl: 'home.html'
})

export class HomePage {

	constructor(public navCtrl: NavController, shareService: ShareService, public events: Events) {
        // Sharing data using service
		shareService.setUserName('Jimmy','Janson');

		// Sharing data with Emiter. 
		// It works only if reciving page has aleady been loaded. 
		// So in this case I'm sending it from the Second Page to the Home Page (backwards)
		events.subscribe('shareObject', (dummy, dummyNumber) => {
			console.log('Welcome', dummy.firstName, 'at', dummyNumber);
		});			
	}

	changePage(event) {
		// Sharing data using NavController
		this.navCtrl.push(SecondPage, {
			param1: 'John', param2: 'Johnson'
		});
	}   
}

 
home.html
<ion-header>
  <ion-navbar>
    <ion-title>The Home Page</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
	 <button ion-button full color="primary" (click)="changePage()" full>Change Page</button>
</ion-content>
 
second.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { ShareService } from '../../services/share/share';

@IonicPage()
@Component({
	selector: 'page-second',
	templateUrl: 'second.html',
})

export class SecondPage {

	parameter1: string;
	parameter2: string;
	serviceData: string;

	constructor(public navCtrl: NavController, public navParams: NavParams, shareService: ShareService, public events: Events) {
		// Receiving data via navController
		this.parameter1 = navParams.get('param1'); 
		this.parameter2 = navParams.get('param2');
		
		// Receiving data via Service
		this.serviceData = shareService.getUserName();

		// Sending data to the Home page via Emiter
		let dummy = {
			firstName: "Jack",
			lastName: "Bauer"
		}

		events.publish("shareObject", dummy, 2);			
	}
}
 
second.html
<ion-header>
	<ion-navbar>
		<ion-title>The Second Page</ion-title>
	</ion-navbar>
</ion-header>


<ion-content padding>
	<h3>The First Solution</h3>
	Welcome {{parameter1}} {{parameter2}}
	<h3>The Second Solution</h3>
	Welcome {{serviceData}}
</ion-content>
 
share.ts
import { Injectable } from '@angular/core';

@Injectable()
export class ShareService {
	
    firstName: string;
    lastName: string;

    constructor() {
        this.firstName = 'Blank';
        this.lastName = 'Name';
    }
 
    setUserName(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;       
    }
 
    getUserName() {
        return this.firstName + ' ' + this.lastName;
    }  
}
 
 
 

Deployment

 
Next step, build our application:
 
ionic build android
 
Be careful here, this step may break if you’re behind a firewall. The first execution will take a long time, so be patient.
 
Finally:
 
ionic run android -l -c -s
 
or if you want to check it locally first:
 
ionic serve -l -c -s
 

Download The Code

 
Working GitHub repo link can be found below:
 
GitHub
 
 

Who Am I?

Between working as a senior Java developer in one of the largest insurance companies in the world and traveling, in my free time, I work as a professional mobile development adviser. I'm also a major jQuery Mobile supporter back at StackOverflow and a forum moderator at the official Ionic Framework forum.



  • Warner

    Hi. In this example, you showed us how to pass a string value through service.

    Can you please show us how to pass an object value?

    Thanks.

  • Graciele E. Victor

    Hello Dragan,

    Didn’t change your code (downloaded from github), and when I try to run, I’m getting this error:

    Unexpected token (11:22) while parsing file

  • Adil shaikh

    Hi,
    I get an error No provider for ShareService using the second approach. As I have not included ShareService in providers but included other injected services. Any Help !

    • Sorry for a late response, I was away until few days ago. The main problem was ever changing Ionic 2 beta framework. This code is now updated to latest framework iteration.

      Plus I have switch the code to Truescript.

  • Alugbin Abiodun

    please will this work for javascript as well??

  • jjmahe

    I am impressed : you got me successfully share data between my pages! Thanks a lot!

  • Ewerton Willams

    Hi, this didn’t work for me :/ when I do in another class: this.myAttr = _myService.SomeMethod(), “this.myAttr” becomes undefined instead of receiving the method return.

  • Julien Castrie

    How would you do if you wanted some data class as a service (as you show in your example), and you want those data classes to use under the hood SQLite which would be embedded in another service taking care of connecting to the DB and also having some function to perform the common queries like select, insert, update, delete? My underlying question is “how to use a service in another service”?

  • Sai Krishna Sampath Kumar

    Hey hi. Your blog is really helpful. I’m new to this ionic as well as ionic2. Currently I’m working on ionic-2. Can you help me with creating an alarm app, exactly how it is in android mobiles. I would love to learn those kinda stuffs. Can you do it?

  • TheDanishDude

    Is there a way to handle data outside constructors?

  • Hi, will be an update for the Ionic 2 final? With a little of analysis we can know where every part go but it is a little distracting!

    Thanks for this post.

    • I have update this blog post to Ionic 3 so take a look.

  • Pingback: UXLX: I released an xAPI-enabled app on Android and iOS | K. Anthony: Instructional Designer()