Facebook Native Ads: Ionic 2

Today lets implement Facebook Audience Network’s Native Advertisement in our Ionic 2 application.

Why Native Ad Unit?
A native ad is a custom designed unit that fits seamlessly with your app. If done well, ads can blend in naturally with your interface.

The unique feature of native ads is that they should balance your app’s experience while protecting the integrity of advertisers’ assets.

Related Read: Facebook Banner and Interstitial Ads: Ionic 2

We’ve installed a blank template for this tutorial

ionic start technotip blank --v2

We create a Ionic 2 project by name ‘technotip’ with blank template.

Related Read: Ionic 2 Starter Templates

Audience Network’s Native Ads: Ionic 2


[youtube https://www.youtube.com/watch?v=-wfXpBGbvic]

YouTube Link: https://www.youtube.com/watch?v=-wfXpBGbvic [Watch the Video In Full Screen.]



Package version information:

C:\ionic2\technotip>ionic info
 
Your system information:
 
Cordova CLI: 6.1.1
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.7.0
Xcode version: Not installed

Steps To Follow
Step 1: Install FacebookAds plugin
Step 2: Add Platform
Step 3: Implement Facebook Audience Network’s Native Ad into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network’s ads.

Native Advertising

Note: Make sure to navigate to your ionic 2 project folder before executing any commands.
Example: Our Ionic 2 project name is ‘technotip’, which is inside a folder called ionic2. So I execute all commands once I get inside our project folder.

C:\>cd ionic2
C:\ionic2>cd technotip
C:\ionic2\technotip>ionic serve -l -c

Step 1: Install FacebookAds plugin

ionic plugin add cordova-plugin-facebookads

This installs FacebookAds plugin to our Ionic 2 project.

Step 2: Add Platform

ionic platform add android
 
OR
 
ionic platform add ios

If you are developing ios app, than add ios platform(for this, you must be on a Mac). If you’re developing android app, then add android as platform. If you face any difficulty with this step or in installing Ionic framework, please refer to Ionic 2 Starter Templates video tutorial.

Step 3: Implement Facebook Ads into your Ionic 2 project

Native Advertisement

src/pages/home/home.ts

    platform.ready().then(() => {
      if(FacebookAds)
      {
        FacebookAds.createNativeAd('763416880384578_1139417452784517');
        this.start = 1;
      }
 
      document.addEventListener("onAdLoaded", function(data){
        let temp: any = data;
 
        if(temp.adType == "native")
        {
 
          document.getElementById('adIcon').setAttribute("src", temp.adRes.icon.url);
          document.getElementById('adCover').setAttribute("src", temp.adRes.coverImage.url);
          document.getElementById('adTitle').innerHTML = temp.adRes.title;
          document.getElementById('adBody').innerHTML = temp.adRes.body;
          document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
          document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
        }
 
      });
 
    });

Pass-in native ad units adId to createNativeAd() method. Now add a listener to onAdLoaded event. This event emits bunch of ad data, which we capture and embed into our view.

Here is the data structure(with Facebook Native Test Ad Data) of the emitted data.

 {
    "isTrusted":false,
    "adNetwork":"FacebookAds",
    "adEvent":"onAdLoaded",
    "adType":"native",
    "adId":"763416880384578_1139417452784517",
    "adRes":{"title":"Facebook Test Ad",
             "socialContext":"Get it on Google Play",
             "buttonText":"Install Now",
             "body":"Your ad integration works. Woohoo!",
             "coverImage":{ "url":"https://www.facebook.com/images/ads/network/test_video_banner.png",
                            "width":414,
                            "height":232},
             "icon":{"url":"https://scontent.xx.fbcdn.net/hphotos-xaf1/t39.3079-6/851551_836527893040166_1350205352_n.png",
                     "width":128,
                     "height":128
                     }
             }
}

We check to see if it is a native ad data. If so, we’ll further fetch and assign ad elements to view elements using Javascript.

Full Source Code: src/pages/home/home.ts

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { Platform } from 'ionic-angular';
 
declare var FacebookAds: any;
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
 start: any = 0;
 
  constructor(public navCtrl: NavController, platform: Platform) {
    platform.ready().then(() => {
      if(FacebookAds)
      {
        FacebookAds.createNativeAd('763416880384578_1139417452784517');
        this.start = 1;
      }
 
      document.addEventListener("onAdLoaded", function(data){
        let temp: any = data;
 
        if(temp.adType == "native")
        {
 
          document.getElementById('adIcon').setAttribute("src", temp.adRes.icon.url);
          document.getElementById('adCover').setAttribute("src", temp.adRes.coverImage.url);
          document.getElementById('adTitle').innerHTML = temp.adRes.title;
          document.getElementById('adBody').innerHTML = temp.adRes.body;
          document.getElementById('adSocialContext').innerHTML = temp.adRes.socialContext;
          document.getElementById('adBtn').innerHTML = temp.adRes.buttonText;
        }
 
      });
 
    });
  }
}

Make sure to have global declaration of FacebookAds variable.

View Code: src/pages/home/home.html

  < span id="native" *ngIf="start != 0">
    < ion-card>
      < img src="" id="adCover" style="max-width: 100%; height: auto;" />
      < ion-card-content text-wrap>
        < ion-item>
          < ion-avatar item-left>
            < img src="" id="adIcon" />
          < /ion-avatar>
          < h2 id="adTitle">
          < p id="adBody">
        < /ion-item>
        < ion-row>
          < ion-col center text-left width-70 small style="font-size: x-small;">
            < span id="adSocialContext" small>< /span>
          < /ion-col>
          < ion-col center text-right width-30>
            < button ion-button small color="secondary" id="adBtn">
            < /button>
          < /ion-col>
        < /ion-row>
      < /ion-card-content>
    < /ion-card>
  < /span>

Here am adding a simple ion-card item with cover image and ion-avatar. We’ve added id’s to each of the elements and will fill the value once the ad data is emitted by onAdLoaded event.

Important Note: This is part 1 of implementing Native Ad. Next we need to implement Clickable area of the ad by using setNativeAdClickArea(adId, x, y, w, h) method. If anyone of you have implemented the Clickable area code for Native Ad, then kindly share your knowledge in the comment section – that would help a lot of us.

I’ve implemented Facebook Native Ads Clickable Area: Ionic 2.

Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network ads

ionic run android -l -c

If you include -l and -c options while installing the project to your device, then you’ll get the live reload and log facility. But you need to be connected to the same network as your terminal where you’re ionic 2 project is running. For Example: Same WiFi for your device as well as your terminal. If your computer is using WiFi and your mobile is using service providers Data connection then this won’t work – in such case use ionic run android command, and you won’t get live reload and log information in the terminal.

Troubleshoot
If you’re getting following errors:
cordova_not_found

OR

int org.json.JSONObject.length() on null

Check these 3 things:
1. You’ve installed proper plugin. Check using ionic plugin list command.
2. You’ve declared FacebookAds variable at the top of the component file.
3. You’ve wrapped the plugins service code inside platform.ready() method.

If all above 3 conditions are set right, then try this:

Remove platform and add it once again.

ionic platform rm android
ionic platform add android

Now install the project ionic run android -l -c to your device and check.

Important Note: Most Ionic plugins work only on the real devices, so do not try to test it using browsers.

I’ve implemented Facebook Native Ads Clickable Area: Ionic 2.

Facebook Banner and Interstitial Ads: Ionic 2

Today lets implement Facebook Audience Network’s Banner Ads and Interstitial Ads in our Ionic 2 project.

We’ve installed a blank template for this tutorial

ionic start technotip blank --v2

We create a Ionic 2 project by name ‘technotip’ with blank template.

Related Read: Ionic 2 Starter Templates

Audience Network’s Banner Ads and Interstitial Ads: Ionic 2


[youtube https://www.youtube.com/watch?v=nU5iUw3xwz4]

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



Package version information:

C:\ionic2\technotip>ionic info
 
Your system information:
 
Cordova CLI: 6.1.1
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.7.0
Xcode version: Not installed

Steps To Follow
Step 1: Install FacebookAds plugin
Step 2: Add Platform
Step 3: Implement Facebook Audience Network’s Ads into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network’s ads.

Facebook Audience Network Ads Ionic2

Note: Make sure to navigate to your ionic 2 project folder before executing any commands.
Example: Our Ionic 2 project name is ‘technotip’, which is inside a folder called ionic2. So I execute all commands once I get inside our project folder.

C:\>cd ionic2
C:\ionic2>cd technotip
C:\ionic2\technotip>ionic serve -l -c

Step 1: Install FacebookAds plugin

ionic plugin add cordova-plugin-facebookads

This installs FacebookAds plugin to our Ionic 2 project.

Step 2: Add Platform

ionic platform add android
 
OR
 
ionic platform add ios

If you are developing ios app, then add ios platform(for this, you must be on a Mac). If you’re developing android app, then add android as platform. If you face any difficulty with this step or in installing Ionic framework, please refer to Ionic 2 Starter Templates video tutorial.

Step 3: Implement Facebook Ads into your Ionic 2 project
1. Banner Ads

To show banner ads in all the views of our app, we need to code it inside src/app/app.component.ts

   if(FacebookAds)
      {
        let options = {
          adId: '763416880384578_1088816394511290',
          adSize: 'SMART_BANNER',
          isTesting: false,
          autoShow: true
        };
        FacebookAds.createBanner(options, function(data){
          FacebookAds.showBanner(8);
        }, function(err){});
      }

Pass configuration information to createBanner() method as first parameter. Second parameter is a success callback and third parameter is an error callback. Inside success callback, we can call showBanner() method which takes position number as a parameter.

isTesting – takes boolean value. It is set to true while development and set to false in production. Default value is false.

FacebookAds Object Value

{
"AD_SIZE":
    {
        "SMART_BANNER":"SMART_BANNER",
        "BANNER":"BANNER",
        "MEDIUM_RECTANGLE":"MEDIUM_RECTANGLE",
        "FULL_BANNER":"FULL_BANNER",
        "LEADERBOARD":"LEADERBOARD",
        "SKYSCRAPER":"SKYSCRAPER"},
 "AD_POSITION":
    {
        "NO_CHANGE":0,
        "TOP_LEFT":1,
        "TOP_CENTER":2,
        "TOP_RIGHT":3,
        "LEFT":4,
        "CENTER":5,
        "RIGHT":6,
        "BOTTOM_LEFT":7,
        "BOTTOM_CENTER":8,
        "BOTTOM_RIGHT":9,
        "POS_XY":10
    }
}

Configure your FacebookAds options using above values.

Important Note: If you’re placing any Ionic Native Plugins code inside constructor, then make sure to wrap it around Platform.ready() method orelse it’ll start throwing errors. Since code inside constructor executes as soon as the class is instantiated, the external libraries might not yet have loaded, which causes the code inside constructor to break. If we wrap the code inside platform ready, the code executes only after the device platform is ready.

Full Source Code: src/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { HomePage } from '../pages/home/home';
 
declare var FacebookAds: any;
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;
  constructor(platform: Platform) {
    platform.ready().then(() => {
      if(FacebookAds)
      {
        let options = {
          adId: '763416880384578_1088816394511290',
          adSize: 'SMART_BANNER',
          isTesting: false,
          autoShow: true
        };
        FacebookAds.createBanner(options, function(data){
          FacebookAds.showBanner(8);
        }, function(err){
          console.log(JSON.stringify(err));
        });
      }
    });
  }
}

Make sure to declare FacebookAds variable(of type any) at the top.

2. Interstitial Ad
We shall invoke an interstitial ad once the user clicks on a button – for demo purpose.

src/pages/home/home.html

  < p>
    < button ion-button (click)="loadAd();">Show Ad< /button>
  < /p>

We’ve added the button to our UI. Once the user clicks on the button, we invoke loadAd() method.

src/pages/home/home.ts

  loadAd(){
    if(FacebookAds)
    {
      let options = {
        adId: '763416880384578_900057893387142'
      };
      FacebookAds.prepareInterstitial(options, function(data){
        FacebookAds.showInterstitial();
      }, function(err){})
    }
  };

we pass interstitial ad units adId to prepareInterstitial() method and then once the success callback is returned we invoke showInterstitial() method.

Full Source Code: src/pages/home/home.ts

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { Platform } from 'ionic-angular';
 
declare var FacebookAds: any;
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
 
  constructor(public navCtrl: NavController, platform: Platform) {
    platform.ready().then(() => {});
  }
  loadAd(){
    if(FacebookAds)
    {
      let options = {
        adId: '763416880384578_900057893387142'
      };
      FacebookAds.prepareInterstitial(options, function(data){
        FacebookAds.showInterstitial();
      }, function(err){})
    }
  };
}

Make sure to declare FacebookAds variable at the top of home component.

other methods:

FacebookAds.removeBanner();
FacebookAds.showBannerAtXY(x, y);
FacebookAds.hideBanner();

Step 4: Install your Ionic 2 app to your device to test Facebook Audience Network ads

ionic run android -l -c

If you include -l and -c options while installing the project to your device, then you’ll get the live reload and log facility. But you need to be connected to the same network as your terminal where you’re ionic 2 project is running. For Example: Same WiFi for your device as well as your terminal. If your computer is using WiFi and your mobile is using service providers Data connection then this won’t work – in such case use ionic run android command, and you won’t get live reload and log information in the terminal.

Troubleshoot
If you’re getting following errors:
cordova_not_found

OR

int org.json.JSONObject.length() on null

Check these 3 things:
1. You’ve installed proper plugin. Check using ionic plugin list command.
2. You’ve declared FacebookAds variable at the top of the component file.
3. You’ve wrapped the plugins service code inside Platform.ready() method.

If all above 3 conditions are set right, then try this:

Remove platform and add it once again.

ionic platform rm android
ionic platform add android

Now install the project ionic run android -l -c to your device and check.

Important Note: Most Ionic plugins work only on the real devices, so do not try to test it using browsers.

Adding AdMob In Ionic 2

Today lets implement AdMob’s Banner Ads, Interstitial Ads and Rewarded Interstitial or Rewarded Video Ads in our Ionic 2 application.

We’ve installed a blank template for this tutorial

ionic start technotip blank --v2

We create a Ionic 2 project by name ‘technotip’ with blank template.

Related Read: Ionic 2 Starter Templates

Ionic Native
You need to make little changes in plugin installation procedures. Watch Using Ionic Native: Ionic 2 video tutorial to know more.

Implementing AdMob Ads In Ionic 2


[youtube https://www.youtube.com/watch?v=Dj2n_25hcko]

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



Package version information:

C:\ionic2\technotip>ionic info
 
Your system information:
 
Cordova CLI: 6.1.1
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.7.0
Xcode version: Not installed

Steps To Follow
Step 1: Install AdMobPro plugin
Step 2: Add Platform
Step 3: Implement AdMob into your Ionic 2 project
Step 4: Install your Ionic 2 app to your device to test AdMob ads.

ionic2-admob

Note: Make sure to navigate to your ionic 2 project folder before executing any commands.
Example: Our Ionic 2 project name is ‘technotip’, which is inside a folder called ionic2. So I execute all commands once I get inside

C:\>cd ionic2
C:\ionic2>cd technotip
C:\ionic2\technotip>ionic serve -l -c

Step 1: Install AdMobPro plugin

ionic plugin add cordova-plugin-admobpro

This installs AdMobPro plugin to our Ionic 2 project.

Step 2: Add Platform

ionic platform add android
 
OR
 
ionic platform add ios

If you are developing ios app, then add ios platform(for this, you must be on a Mac). If you’re developing android app, then add android as platform. If you face any difficulty with this step or in installing Ionic framework, please refer to Ionic 2 Starter Templates video tutorial.

Step 3: Implement AdMob into your Ionic 2 project
1. Banner Ads

To show banner ads in all the views of our app, we need to code it inside src/app/app.component.ts

import { AdMob } from 'ionic-native';

Import AdMob Class.

      let options = {
        adId: 'ca-app-pub-5732334124058455/7973166445',
        adSize: 'SMART_BANNER',
        isTesting: false
      };
 
      AdMob.createBanner(options).then(() => {
        AdMob.showBanner(8);
      });

Pass configuration information to createBanner method which returns a promise. After configuring the Banner information call showBanner method and pass the ad position number.

adId – must be AdMob ads banner id.
adSize – Takes following values SMART_BANNER, BANNER, MEDIUM_RECTANGLE, FULL_BANNER, LEADERBOARD, SKYSCRAPER, or CUSTOM. By default it takes the value ‘SMART_BANNER’.
isTesting – Give it true in development and false to show real ads in production.

showBanner method takes a number as parameter.
0 – NO_CHANGE;
1 – TOP_LEFT;
2 – TOP_CENTER;
3 – TOP_RIGHT;
4 – LEFT;
5 – CENTER;
6 – RIGHT;
7 – BOTTOM_LEFT;
8 – BOTTOM_CENTER;
9 – BOTTOM_RIGHT;
10 – POS_XY;

Important Note: If you’re placing any Ionic Native Plugins code inside constructor, then make sure to wrap it around Platform.ready() method orelse it’ll start throwing errors. Since code inside constructor executes as soon as the class is instantiated, the external libraries might not yet have loaded, which causes the code inside constructor to break. If we wrap the code inside platform ready, the code executes only after the device platform is ready.

Full Source Code: src/app/app.component.ts

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar, Splashscreen, AdMob } from 'ionic-native';
 
import { HomePage } from '../pages/home/home';
 
 
@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage = HomePage;
 
  constructor(platform: Platform) {
    platform.ready().then(() => {
 
      let options = {
        adId: 'ca-app-pub-5732334124058455/7973166445',
        adSize: 'SMART_BANNER',
        isTesting: false
      };
 
      AdMob.createBanner(options).then(() => {
        AdMob.showBanner(8);
      });
 
    });
  }
}

2. Interstitial Ad
We shall invoke an interstitial ad once the user clicks on a button – for demo purpose.

src/pages/home/home.html

  < p>
    < button ion-button (click)="loadAd();">Show Ad< /button>
  < /p>

We’ve added the button to our UI. Once the user clicks on the button, we invoke loadAd() method.

src/pages/home/home.ts

  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/3403366048',
    isTesting: false
   };
    AdMob.prepareInterstitial(options)
         .then(() => {
           AdMob.showInterstitial();
         });
  };

we pass interstitial ad units adId to prepareInterstitial() method and then once the promise is returned we invoke showInterstitial() method. We can even pass isTesting option with true or false Boolean value.

Full Source Code: src/pages/home/home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
 
import { AdMob } from 'ionic-native';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  constructor(public navCtrl: NavController) {
 
  }
  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/3403366048',
    isTesting: false
   };
    AdMob.prepareInterstitial(options)
         .then(() => {
           AdMob.showInterstitial();
         });
  };
}

Make sure to import ‘AdMob’ at the top of home component.

3. Rewarded Interstitial or Rewarded Video Ad

import { Component } from '@angular/core';
 
import { NavController } from 'ionic-angular';
 
import { AdMob } from 'ionic-native';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  constructor(public navCtrl: NavController) {
 
  }
  loadAd(){
   let options = {
    adId: 'ca-app-pub-5732334124058455/7216350441',
    isTesting: false
   };
    AdMob.prepareRewardVideoAd(options)
         .then(() => {
           AdMob.showRewardVideoAd();
         });
  };
}

Pass rewarded interstitial or rewarded video ads adId to prepareRewardVideoAd() method and then invoke showRewardVideoAd() method.

Step 4: Install your Ionic 2 app to your device to test AdMob ads

ionic run android -l -c

If you include -l and -c options while installing the project to your device, then you’ll get the live reload and log facility. But you need to be connected to the same network as your terminal where you’re ionic 2 project is running. For Example: Same WiFi for your device as well as your terminal. If your computer is using WiFi and your mobile is using service providers Data connection then this won’t work – in such case use ionic run android command, and you won’t get live reload and log information in the terminal.

Troubleshoot
If you’re getting following errors:
cordova_not_found

OR

int org.json.JSONObject.length() on null

Check these 3 things:
1. You’ve installed proper plugin. Check using ionic plugin list command.
2. You’ve imported the plugin wherever you’re using its service.
3. You’ve wrapped the plugins service code inside Platform.ready() method.

If all above 3 conditions are set right, then try this:

Remove platform and add it once again.

ionic platform rm android
ionic platform add android

Now install the project ionic run android -l -c to your device and check.

Important Note: Most Ionic Native plugins work only on the real devices, so do not try to test it using browsers.

Tappable Attribute: Ionic 2

It is recommended to use click event only on clickable elements like button or/and on anchor tags. If you use click event on any other tags(apart from button or anchor tag) there will be some kind of jerkiness or delay of 300 milliseconds.

Related Read:
Passing Data Between Pages: Ionic 2

Tappable Attribute: Ionic 2


[youtube https://www.youtube.com/watch?v=d1DzlKu6sUQ]

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



src/home/home.html

  < ion-list>
    < ion-item *ngFor="let Company of companies" 
              (click)="detailsPage(Company.code);" tappable>
      {{Company.name}}
    < /ion-item>
  < /ion-list>

Solution
Add tapabble attribute if you’re using click event on elements other than button or an anchor tag. In our example we are using click event on ion-item element, so adding tapabble attribute would speed up the firing of click event by 300 milliseconds.

In today’s performance centric application development 300 milliseconds delay shouldn’t be neglected. Hope this small tip helps in improving the usability of your mobile application.

Passing Data Between Pages: Ionic 2

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 https://www.youtube.com/watch?v=0JtS8fHR1Co]

YouTube Link: https://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.