Passing Data Between Pages: Ionic 2

Advertisement:

Today lets see how we can pass data between pages in ‘Ionic 2’ application.

Related Read:
Basic Navigation: Ionic 2
Details Arrow: Ionic 2
Basics of Injectable or Providers: Ionic 2

ionic2-passing-data-between-pages

Passing Data Between Pages: Ionic 2



YouTube Link: http://www.youtube.com/watch?v=0JtS8fHR1Co [Watch the Video In Full Screen.]



src/providers/data.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
 
@Injectable()
export class Data {
data: any;
  constructor(public http: Http) {
    this.data = [
      {name: 'Microsoft', code: 324, product: 'Windows 10'},
      {name: 'Apple', code: 678, product: 'iPhone 7'},
      {name: 'Google', code: 567, product: 'Pixel'},
      {name: 'Oracle', code: 89, product: 'RDBMS'},
      {name: 'IBM', code: 542, product: 'Computer Hardware and Software'}
    ];
  }
 
  loadAll(){
      return Promise.resolve(this.data);
  };
  getByID(id){
    for(var i=0; i< (this.data).length; i++)
    {
      if(this.data[i].code == id)
      {
        return Promise.resolve(this.data[i]);
      }
    }
  };
}

Here we have an array variable(data) which has couple of objects which has company name, product name and an unique code associated with each object. We also have loadAll() method which simply returns this data array variable as promise.

We also have another method called getByDI() which receives an argument. Inside this method, we loop thought the array variable(data) and return the matching id’s object as promise.

src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Data } from '../../providers/data';
import { SecondPage } from '../second/second';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  companies: any = 0;
  constructor(public navCtrl: NavController, public data: Data) {
        this.data.loadAll().then(result => {
            this.companies =  result;
        });
  }
  detailsPage(id){
    this.navCtrl.push(SecondPage, {code: id});
  };
}

Here we invoke loadAll() method and assign the returned result to companies variable. We also have detailsPage() method which pushes the SecondPage reference to navigation stack and also assigns the value of id to a property called code(we can name this property anything we want). Also note that we have assigned the initial value of companies variable to zero.

src/pages/home/home.html

  < ion-spinner name="circles" *ngIf="companies == 0">
  < /ion-spinner>
  < ion-list *ngIf="companies != 0" no-lines>
    < ion-item *ngFor="let Company of companies" 
              (click)="detailsPage(Company.code);" detail-push>
      {{Company.name}}
    < /ion-item>
  < /ion-list>

Here we show a spinner component until the promise gets resolved. Once the variable companies has some other value than zero, the list items gets displayed. When the user clicks on any of the list item, we invoke detailsPage() method and also pass in its corresponding unique code to the method.

Generating page using Ionic 2 CLI

ionic g page pageName

src/pages/second/second.ts

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Data } from '../../providers/data';
 
@Component({
  selector: 'page-second',
  templateUrl: 'second.html'
})
export class SecondPage {
  company: any = 0;
  constructor(public navCtrl: NavController, 
              public navParams: NavParams, 
              public data: Data) {
    this.data.getByID(this.navParams.get('code')).then(result => {
      this.company = result;
    });
  }
}

Here we import NavParams class and using the NavParams reference object and its get method we retrieve the value passed in by the home page to second page. We pass this value to getByID() method and receive details of company which has this unique code as id. Also note that we have assigned zero as initial value to the variable company.

src/pages/second/second.html

< ion-spinner name="circles" *ngIf="company == 0">
< /ion-spinner>
< ion-content padding *ngIf="company != 0">
< h2>{{company.name}}< /h2>
< strong>Product: < /strong> {{company.product}}
< /ion-content>

Here we show a spinner component until the promise resolves and the company variable have required results in it.

Important:
1. Make sure to initialize the variables(companies and company variable in our example) and show a spinner or do something with the initial value before trying to access the properties the actual results has – because, if you try to access properties of the result before the promise has resolved, you’ll get errors.
For example: In our example, we have name and product properties. If I try to access company.name and company.product before the promise has resolved we’ll get the error – that the name and property of undefined CAN NOT be accessed.

2. Make sure to import all the pages and providers(in our case pages like homepage, second page and Data provider) inside src/app/app.module.ts file and specify the class names and data provider name in appropriate places/blocks/sections as shown in the video tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *