Ionic [2 & 3] | Sharing & Passing Various Data Between Pages

Written by on June 27, 2019

Ionic [2 & 3] | Sharing & Passing Various Data Between Pages

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
Categories

Leave a Reply