Solution 2 – Permanent Data Sharing

 
Unfortunately, a previous example is not viable if we want to permanently store our data while an application is up and running.
 
To be able to do just that we need to use a service. It’s just another class but without a view component.
 
Here’s how it looks like in this example:
 
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;
    }   
}
 
Be very careful before you go this way. If we include this service using 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 app level, then pass it to child pages/components.
 
This is how we’re going to initialize it in app.js core component:
 
import {ShareService} from './pages/services/ShareService';
 
@Component({
	templateUrl: 'build/app.html',
    providers: [ShareService]	
})
 
providers keyword is the most important line here, this solution will not work without it.
 
We can now use ShareService to store application data:
 
constructor(platform: Platform, private shareService: ShareService) {
 
shareService.setUserName('John','Johnson');
 
On child pages, a code is almost the same. There’s only one difference, do not use providers keyword inside a @Component decorator. You can use it, but it will create another ShareService instance.
 
The first thing we need to do is import ShareService:
 
import {ShareService} from '../services/ShareService';
 
Inject it:
 
constructor(private navController: NavController, private navParams: NavParams, private shareService: ShareService) {
 
Finally, query our stored data:
 
this.serviceData = shareService.getUserName();
 
 
 

Source Code

 
Update: 30.06.2016 (July 30th) - Article and example are updated to match changes made to Ionic 2.0.0-beta.10 version
 
In case GitHub repo is not available and you can only use code provided below, this is what project folder looks like (image taken from Sublime text editor):
 
Ionic 2 Data Share Folder Structure
 
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <title>Ionic</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link ios-href="build/css/app.ios.css" rel="stylesheet">
  <link md-href="build/css/app.md.css" rel="stylesheet">
  <link wp-href="build/css/app.wp.css" rel="stylesheet">
</head>

<body>
  <ion-app></ion-app>

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>
  <!-- Polyfill needed for platforms without Promise and Collection support -->
  <script src="build/js/es6-shim.min.js"></script>
  <!-- Zone.js and Reflect-metadata  -->
  <script src="build/js/Reflect.js"></script>
  <script src="build/js/zone.js"></script>
  <!-- the bundle which is built from the app's source code -->
  <script src="build/js/app.bundle.js"></script>
</body>

</html>
 
app.html
<ion-nav [root]="rootPage"></ion-nav>
 
app.ts
import {Component} from '@angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {Home} from './pages/home/home';
import {ShareService} from './pages/services/ShareService';


@Component({
	templateUrl: 'build/app.html',
    providers: [ShareService]	
})

export class MyApp {
	rootPage: any = Home;

	constructor(platform: Platform, private shareService: ShareService) {
		platform.ready().then(() => {
			// Okay, so the platform is ready and our plugins are available.
			// Here you can do any higher level native things you might need.
			StatusBar.styleDefault();

			shareService.setUserName('John','Johnson');      
		});
	}
}

ionicBootstrap(MyApp);
 
home.html
<ion-header>
  <ion-navbar>
    <ion-title>
      Home Page
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="home" padding>
  <button (click)="changePage($event)" full>Change Page</button>
</ion-content>
 
home.ts
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {SecondPage} from '../secondPage/secondPage';
import {ShareService} from '../services/ShareService';

@Component({
  templateUrl: 'build/pages/home/home.html'
})

export class Home {
  constructor(private navController: NavController) {

  }

  changePage(event) {
    this.navController.push(SecondPage, {
      param1: 'John', param2: 'Johnson'
    });
  }    
}
 
secondPage.html
<ion-header>
  <ion-navbar>
    <ion-title>
      Second Page
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content class="secondPage" padding>
<h3>The First Solution</h3>
Welcome {{parameter1}} {{parameter2}}
<h3>The Second Solution</h3>
Welcome {{serviceData}}
</ion-content>
 
secondPage.ts
import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {ShareService} from '../services/ShareService';

@Component({
  templateUrl: 'build/pages/secondPage/secondPage.html'
})

export class SecondPage {

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

	constructor(private navController: NavController, private navParams: NavParams, private shareService: ShareService) {
	    this.parameter1 = navParams.get('param1'); 
	    this.parameter2 = navParams.get('param2');
	    this.serviceData = shareService.getUserName();
	}    
}
 
ShareService.ts
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
 
 

What to read next

IONIC 2 | How To Create And Validate Forms
 
 

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.

Blogs worth reading

If you're here looking for information related to the Ionic Framework, you will also like these blogs:






  • 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.