This post is about displaying the API records with delete and update actions using new Ionic and Angular reactive programming. This is a continuation of Ionic Angular series and it explains to you how to distribute the data between the components using RxJS method like BehaviorSubject. All of the feed API responses/records storing in a reactive object, This help the application DOM works seamlessly with update and delete operations. Implement this to your side project and enrich your applications.
This article is more about understanding the Event Emitters in Angular and Ionic. Data flow is the most important when you build an application to communicate with components. Event Emitters will help you to even bind using @Input @Output decorators. Here is a simple example to display and update the user profile using Angular Event Emitters. For this demo I choose Ionic framework for a better experience. Take a quick look at the live demo.
Node Express web framework is the best solution to create RESTful APIs in a quick time. Previously we published some concepts with different technologies like PHP and Java. This article will explain to you a more simple way to use external plugins to enrich your project APIs. Here you will find to create GET and POST requests with request payload validations to protect the endpoints.
This is step by step tutorial Ionic 3 and Angular 4 app authentication with Ionic 3 native Google plus plugin. Before started with the app, there's a setup of Google Plus via Google Developer Console.
1. Google API Setup
The first thing to setup from Google is generating configuration files for iOS and Android. For iOS, open your browser then point to this address then log in with your google account.
Create the new iOS app from there by filling the form. Enter app name and iOS bundle ID, our example is "MyGooglePlusAuth" for app name and "com.mygoogleplusauth" for iOS bundle ID. Please, remember that iOS bundle ID will use in Ionic 3 config later and that would be easy if we use the same bundle ID for Android.
Leave other option to default then click "Choose and Configure Service" button.
Click "ENABLE GOOGLE SIGN IN" button. After that, click "Generate configuration file" button. Click the button "Download GoogleService-info.plist", we will use this files later on the Ionic 3 project.
Next, we have to generate Google service configuration file for Android too. Go to this address then choose app name that previously created. File Android package name same as iOS bundle ID "com.mygoogleplusauth".
Click "Choose and configure service" button. Before enabling this service, we have to create new SHA-1 signing certificate which uses for release and debug. Open terminal or command line, then type this command to create certificate fingerprint for debugging.
keytool -exportcert -list -v \
> -alias androiddebugkey -keystore ~/.android/debug.keystore
or from the command line (windows).
keytool -exportcert -list -v \
-alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
Enter the password, by default for "debug.keystore is "android".
Alias name: androiddebugkey
Creation date: Nov 8, 2015
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 5e9752f4
Valid from: Sun Nov 08 22:25:34 WIB 2015 until: Tue Oct 31 22:25:34 WIB 2045
Certificate fingerprints:
MD5: 0A:2D:96:6B:B8:84:F7:37:2E:7E:83:09:43:BB:B7:D4
SHA1: 2B:52:02:F0:82:94:34:68:FC:B6:DD:81:1D:3A:66:D7:57:3B:B9:11
SHA256: B1:40:EB:9D:03:50:A2:0F:F2:D4:1B:6D:AA:F6:F9:6A:57:52:B0:70:5A:3C:87:9E:15:F0:BE:7C:90:00:DA:51
Signature algorithm name: SHA256withRSA
Version: 3
Extensions:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: C0 3A D3 06 65 23 89 A1 5D 80 CC 55 88 D8 BD 23 .:..e#..]..U...#
0010: 80 6E 67 01 .ng.
]
]
Copy Certificate fingerprints SHA1 value then paste in "Android Signing Certificate SHA-1" of Google Developer to enable Google Sign-In service.
Next, just click the "CLOSE" button and not necessary to download generated configuration files for Android only. If you plan to use your app in production/published, change the certificate fingerprint with this command.
keytool -exportcert -list -v \
-alias <your-key-name> -keystore <path-to-production-keystore>
Keystore using same as your Keystore of build release for publishing. Then edit manually in Google developer console. Choose credentials from side menu then find "OAuth 2.0 client IDs" for Android. You can replace the SHA1 certificate fingerprint with production/release key.
2. Create Ionic 3 App
As usually in almost all of our tutorial, we create an app from scratch. Back to the terminal or command line then go to your apps folder. Type this command to create new Ionic 3 app.
ionic start mygoogleplusauth blank --v2
Go to the newly created app folder.
cd mygoogleplusauth
Now, open and edit config.xml in the root of app folder. Replace app id on the <widget> tag to match Android package or iOS bundle ID that previously created on the Google Developer page.
<widget id="com.mygoogleplusauth" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
Run the app, to make sure everything still on the path.
ionic serve -l
If you see the Ionic 3 blank app page below then we ready to continue.
For now, stop the app by push control+c at the same time.
3. Setup Ionic 3 Native Google Plus Plugin
To install Ionic 3 native Google Plus plugin you can refer to the official Ionic Framework documentation. Back to the terminal or command line. Type this command to install Cordova plugin and ionic module of Google Plus plugin. You can find "REVERSED_CLIENT_ID" on generated "GoogleService-info.plist" file.
ionic plugin add cordova-plugin-googleplus --variable REVERSED_CLIENT_ID=myreversedclientid
npm install --save @ionic-native/google-plus
If you see warning like below then we should update the "@ionic-native/core" module.
npm WARN @ionic-native/google-plus@3.6.1 requires a peer of @ionic-native/core@^3.6.1 but none was installed.
Update the @ionic-native/core module by type this commands.
npm uninstall --save @ionic-native/core
npm install --save @ionic-native/core@^3.6.1
4. Add Google Login Button on The Page
To implement Google authentication, we put Google login button to trigger Google Plus authentication. Open and edit "src/pages/home/home.ts" then replace all codes with this.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { GooglePlus } from '@ionic-native/google-plus';
@Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [GooglePlus]
})
export class HomePage {
displayName: any;
email: any;
familyName: any;
givenName: any;
userId: any;
imageUrl: any;
isLoggedIn:boolean = false;
constructor(public navCtrl: NavController, private googlePlus: GooglePlus) {
}
login() {
this.googlePlus.login({})
.then(res => {
console.log(res);
this.displayName = res.displayName;
this.email = res.email;
this.familyName = res.familyName;
this.givenName = res.givenName;
this.userId = res.userId;
this.imageUrl = res.imageUrl;
this.isLoggedIn = true;
})
.catch(err => console.error(err));
}
logout() {
this.googlePlus.logout()
.then(res => {
console.log(res);
this.displayName = "";
this.email = "";
this.familyName = "";
this.givenName = "";
this.userId = "";
this.imageUrl = "";
this.isLoggedIn = false;
})
.catch(err => console.error(err));
}
}
Next, open and edit "src/pages/home/home.ts" then replace all codes with this.
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<div *ngIf="isLoggedIn; else loginTemplate">
<h1>Welcome, {{displayName}}!</h1>
<p>Email: {{email}}<br>
Family Name: {{familyName}}<br>
Given Name: {{givenName}}<br>
User ID: {{userId}}</p>
<p><ion-avatar item-left>
<img src="{{imageUrl}}">
</ion-avatar></p>
<p><button ion-button (click)="logout()">Logout From Google</button></p>
</div>
<ng-template #loginTemplate>
<h1>Please Login to see your Google Account Information</h1>
<p><button ion-button (click)="login()">Login With Google</button></p>
</ng-template>
</ion-content>
For android is really easy. Before run make sure we have to add Android platform.
ionic platform add android
Then run the app on Android device, make sure you have connected your device to your computer.
ionic run android
After clicking the button "Login With Google", it will show a dialog to choose your existing google credentials on the device. Choose one of it then it will back to the app with Google user detail.
For iOS type this command.
ionic build ios
After the finished build, open the file with extension ".xcodeproj" on "/platforms/ios" folder using XCode.
Click/highlight project name on the left pane, then choose Capabilities. Turn on Keychain Sharing, for that you have to use your Apple developer account.
Now, we can run the app to an iOS device from XCode, make sure there's a Google account on the device.
That it's for now, you can find the full source code on GitHub.
Thanks!
This is an example of a multi-level accordion menu with dynamic data using latest Ionic 3 and Angular 4.
1. Create New Ionic 3 and Angular 4 Side Menu App
We will start this tutorial by creating new Ionic 3 and Angular 4 app. This time we will use generated side menu app. Open and edit the terminal or Node.js command line then type this command.
ionic start ionic3-accordion-menu sidemenu --v2
That command will create new Ionic 3 app with the name 'ionic3-accordion-menu' using default template 'sidemenu'. Go to the newly created app folder.
cd ionic3-accordion-menu
Run the Ionic 3 app on the browser.
ionic serve -l
You should see this side menu.
Right now, we will skip lazy loading pages configuration because we will focus only on the multilevel accordion menu. You can find more about lazy loading and Ionic 3 getting started here.
2. Create Nested Array of Objects
We have to create nested Array of objects which it's contains multilevel arrays. Create a new folder and JSON file in asset folder.
mkdir src/assets/data
touch src/assets/data/menus.json
Open and edit 'menus.json' then add this lines of data.
[
{
"category":"PC",
"subs": [
{
"subcategory":"Processor",
"manufactures": [
{
"manufacture":"Intel"
},
{
"manufacture":"AMD"
}
]
},
{
"subcategory":"Motherboard",
"manufactures": [
{
"manufacture":"Asus"
},
{
"manufacture":"AMD"
},
{
"manufacture":"GigaByte"
},
{
"manufacture":"Intel"
}
]
},
{
"subcategory":"Memory",
"manufactures": [
{
"manufacture":"Visipro"
},
{
"manufacture":"Crucial"
},
{
"manufacture":"VenomRX"
}
]
}
]
},
{
"category":"Laptop",
"subs": [
{
"subcategory":"Notebook",
"manufactures": [
{
"manufacture":"Lenovo"
},
{
"manufacture":"Dell"
}
]
},
{
"subcategory":"Netbook",
"manufactures": [
{
"manufacture":"Lenovo"
},
{
"manufacture":"Dell"
},
{
"manufacture":"Acer"
},
{
"manufacture":"HP"
}
]
}
]
},
{
"category":"Printer",
"subs": [
{
"subcategory":"Laserjet",
"manufactures": [
{
"manufacture":"HP"
},
{
"manufacture":"Brother"
},
{
"manufacture":"Canon"
},
{
"manufacture":"Samsung"
}
]
},
{
"subcategory":"Deskjet",
"manufactures": [
{
"manufacture":"HP"
},
{
"manufacture":"Canon"
},
{
"manufacture":"Epson"
}
]
}
]
}
]
3. Create and Call Service/Provider for Accessing Data
To access JSON data we have to create new service or provider to keep app modular. Type this command to create it.
ionic g provider DataService
Open and edit 'src/providers/data-service.ts' add 'Response' to 'Http' import.
import { Http, Response } from "@angular/http";
Create this function for call JSON data.
getMenus(){
return this.http.get('assets/data/menus.json')
.map((response:Response)=>response.json());
}
Register this service in 'app.module.ts' by open and edit 'src/app/app.module.ts' then add this import.
import { HttpModule } from '@angular/http';
import { DataService } from '../providers/data-service';
Add 'HttpModule' in '@NgModule' imports.
...
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
],
...
Add 'DataService' in '@NgModule' providers.
...
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
DataService
]
...
Because menu holds by component, we have to edit it to call data for the menu from service/provider. Open and edit 'src/app/app.component.ts' then add this import.
import { DataService } from '../providers/data-service';
Replace this line.
pages: Array<{title: string, component: any}>;
With this.
pages: any;
Now, inject 'DataService' in constructor parameter and add this function for calling JSON data inside of constructor.
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public dataService: DataService) {
this.initializeApp();
this.dataService.getMenus()
.subscribe((response)=> {
this.pages = response;
console.log(this.pages);
});
}
4. Create Multilevel Accordion Menu
Now, is the point. Creating multilevel Accordion Menu with Ionic 3 and Angular 4. Open and edit 'src/app/app.html' the add this lines of codes inside '<ion-content>'.
<ion-content>
<ion-list>
<ion-item *ngFor="let p of pages" text-wrap>
{{p.category}}
<ion-list>
<ion-item *ngFor="let s of p.subs" text-wrap>
{{s.subcategory}}
<ion-list>
<ion-item *ngFor="let m of s.manufactures" text-wrap>
{{m.manufacture}}
</ion-item>
</ion-list>
</ion-item>
</ion-list>
</ion-item>
</ion-list>
</ion-content>
After we re-run the Ionic 3 app, the menu should look like this.
As you can see, there is 3 level of the menu. For that, we have to make accordion to hide child menus. Open and edit 'src/app/app.component.ts' then declare this variable.
showLevel1 = null;
showLevel2 = null;
Create new functions for toggle show/hide level 2 and level 3 of the menu.
toggleLevel1(idx) {
if (this.isLevel1Shown(idx)) {
this.showLevel1 = null;
} else {
this.showLevel1 = idx;
}
};
toggleLevel2(idx) {
if (this.isLevel2Shown(idx)) {
this.showLevel1 = null;
this.showLevel2 = null;
} else {
this.showLevel1 = idx;
this.showLevel2 = idx;
}
};
Also, create the function for check if level 2 and 3 is shown or hidden.
isLevel1Shown(idx) {
return this.showLevel1 === idx;
};
isLevel2Shown(idx) {
return this.showLevel2 === idx;
};
Now, open and edit 'src/app/app.html' then replace all list with this list.
<ion-content>
<ion-list>
<ion-item *ngFor="let p of pages; let i=index" text-wrap (click)="toggleLevel1('idx'+i)" [ngClass]="{active: isLevel1Shown('idx'+i)}">
<h4>
{{p.category}}
<ion-icon color="success" item-right [name]="isLevel1Shown('idx'+i) ? 'arrow-dropdown' : 'arrow-dropright'"></ion-icon>
</h4>
<ion-list *ngIf="isLevel1Shown('idx'+i)">
<ion-item *ngFor="let s of p.subs; let i2=index" text-wrap (click)="toggleLevel2('idx'+i+'idx'+i2)" [ngClass]="{active: isLevel2Shown('idx'+i+'idx'+i2)}">
<h4>
{{s.subcategory}}
<ion-icon color="success" item-right [name]="isLevel2Shown('idx'+i+'idx'+i2) ? 'arrow-dropdown' : 'arrow-dropright'"></ion-icon>
</h4>
<ion-list *ngIf="isLevel2Shown('idx'+i+'idx'+i2)">
<ion-item *ngFor="let m of s.manufactures" text-wrap>
{{m.manufacture}}
</ion-item>
</ion-list>
</ion-item>
</ion-list>
</ion-item>
</ion-list>
</ion-content>
Then re-run the Ionic 3 app and see the results in the browser.
You can find the source code on our GitHub.
Thanks.
After play around with new Ionic 3 and Angular 4 in the previous tutorial, now we started the step by step tutorial of Ionic 3, Angular 4 and Google Maps Directions Service using Google Maps Javascript API.
1. Create New Ionic 3 and Angular 4 App
As usually, we are starting our tutorial from scratch. We assume that your computer or environment already have Node.js installed. Now, open the terminal or Node.js command line then type this command to install new Ionic 3 and Cordova.
sudo npm install -g cordova ionic
Now, go to project folders then type this command to make a new Ionic 3 App.
ionic start ionic3-googlemaps-directions blank --v2
Go to the newly created app folder.
cd ionic3-googlemaps-directions
This time we will modify few default files to implements lazy loading pages. Open and edit 'src/app/app.module.ts' then remove imports, NgModule-declaration and NgModule-entryComponents of page Home. So, this file will looks like this.
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';
@NgModule({
declarations: [
MyApp
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
Add new file 'src/pages/home/home.module.ts'.
touch src/pages/home/home.module.ts
Open and edit that file then add this lines of codes.
import { NgModule } from '@angular/core';
import { HomePage} from './home';
import { IonicPageModule } from 'ionic-angular';
@NgModule({
declarations: [HomePage],
imports: [IonicPageModule.forChild(HomePage)],
entryComponents: [HomePage]
})
export class HomePageModule { }
Now, open and edit 'src/pages/home/home.ts' then add this import.
import { IonicPage } from 'ionic-angular';
Then add annotation of IonicPage before component annotation.
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
Next, open and edit 'src/app/app.component.ts' then remove import of HomePage and change reference to HomePage component to be 'HomePage' string.
import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: string = 'HomePage';
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
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();
splashScreen.hide();
});
}
}
Now, run the app.
ionic serve -l
You should see this page in the browser.
2. Setup Google Maps and Google Maps Directions Service on Google Developer Console
Before setup Google Maps and Directions Service in the Ionic 3 and Angular 4 app, we have to make sure that Google Maps Javascript API and Google Maps Directions Service is enabled on Google Developer console.
Open your browser then go to Google Developer Console then click Enable API to enable Google Maps Javascript API and Google Maps Directions.
After enabling Google Maps and Google Maps Directions then Go to Credentials page by click on Credentials left the menu. Make sure that you have Browser Key, if not create Browser key by click on Create Credentials button.
Write down the key on a notepad or any text editor, because we will use it later on the app.
3. Implement Google Maps and Google Maps Directions Service on The Ionic 3 App
Now, it's time to implement Google Maps and Google Maps Directions Service on the Ionic 3 app. Starting with reference Javascript library of Google Maps in 'src/index.html'. Open and edit 'src/index.html' then add this script reference before the closing of the body tag.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Change 'YOUR_API_KEY' with the key that previously written in the text editor.
Next, open and edit 'src/pages/home/home.html' then replace all tags inside 'ion-content' with this lines of tags.
<ion-content>
<div id="floating-panel">
<b>Start: </b>
<select [(ngModel)]="start" id="start" (change)="calculateAndDisplayRoute()">
<option value="chicago, il">Chicago</option>
<option value="st louis, mo">St Louis</option>
<option value="joplin, mo">Joplin, MO</option>
<option value="oklahoma city, ok">Oklahoma City</option>
<option value="amarillo, tx">Amarillo</option>
<option value="gallup, nm">Gallup, NM</option>
<option value="flagstaff, az">Flagstaff, AZ</option>
<option value="winona, az">Winona</option>
<option value="kingman, az">Kingman</option>
<option value="barstow, ca">Barstow</option>
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select><br>
<b>End: </b>
<select [(ngModel)]="end" id="end" (change)="calculateAndDisplayRoute()">
<option value="chicago, il">Chicago</option>
<option value="st louis, mo">St Louis</option>
<option value="joplin, mo">Joplin, MO</option>
<option value="oklahoma city, ok">Oklahoma City</option>
<option value="amarillo, tx">Amarillo</option>
<option value="gallup, nm">Gallup, NM</option>
<option value="flagstaff, az">Flagstaff, AZ</option>
<option value="winona, az">Winona</option>
<option value="kingman, az">Kingman</option>
<option value="barstow, ca">Barstow</option>
<option value="san bernardino, ca">San Bernardino</option>
<option value="los angeles, ca">Los Angeles</option>
</select>
</div>
<div #map id="map"></div>
</ion-content>
The most important thing when using Google Maps in HTML is specifying the height of the map element 'DIV', otherwise the maps will never shown. For that, open and edit 'src/pages/home/home.scss' then make it like this.
page-home {
#floating-panel {
position: absolute;
top: 10px;
right: 5px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
#map {
height: 100%;
}
}
Open and edit 'src/pages/home/home.ts' then replace all codes with this codes.
import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage } from 'ionic-angular';
import { NavController } from 'ionic-angular';
declare var google;
@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild('map') mapElement: ElementRef;
map: any;
start = 'chicago, il';
end = 'chicago, il';
directionsService = new google.maps.DirectionsService;
directionsDisplay = new google.maps.DirectionsRenderer;
constructor(public navCtrl: NavController) {
}
ionViewDidLoad(){
this.initMap();
}
initMap() {
this.map = new google.maps.Map(this.mapElement.nativeElement, {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
this.directionsDisplay.setMap(this.map);
}
calculateAndDisplayRoute() {
this.directionsService.route({
origin: this.start,
destination: this.end,
travelMode: 'DRIVING'
}, (response, status) => {
if (status === 'OK') {
this.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
}
To run the Ionic 3 app on the browser, type this command.
ionic serve -l
You should see this page.
When you change to start, end or both select box, the map should show directions like this.
To run the Ionic 3 app on the device, don't forget to re-add platforms.
ionic platform rm ios
ionic platform add ios
ionic platform rm android
ionic platform add android
Finally, run the Ionic 3 app on the device.
ionic run android
or
ionic run ios
If you see same as the browser, then everything is working properly.
You can find the source code on our GitHub.
Thanks!
Today we will share step by step tutorial on what we are experiencing in the real Ionic project of upgrade Ionic and Angular 4 to Ionic 3 and Angular 4. There's a little different than describe on official guides. We are more comfortable do an upgrade by creating new Ionic 3 and Angular 4 project rather than modify existing Ionic 2 and Angular 2 project.
1. Create new Ionic 3 App
Open terminal or Node.js command line, go to projects folder then type this command.
ionic start appname sidemenu --v2
That command will create new Ionic 3 app with the name "appname", using side menu template and version still same with Ionic 2 by using "--v2" prefix. Use the same template as previous Ionic 2 app.
Check all default plugins that used on the new Ionic 3 app.
ionic plugin list
You should a see result like this.
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-splashscreen 4.0.2 "Splashscreen"
cordova-plugin-statusbar 2.2.1 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
ionic-plugin-keyboard 2.2.1 "Keyboard"
2. Check Old Ionic 2 App Plugins
Do the same thing as previous step.
ionic plugin list
Now, you can see different with default plugin that use by Ionic 3.
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-fcm 2.1.1 "FCMPlugin"
cordova-plugin-inappbrowser 1.6.1 "InAppBrowser"
cordova-plugin-splashscreen 4.0.1 "Splashscreen"
cordova-plugin-statusbar 2.2.1 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
ionic-plugin-keyboard 2.2.1 "Keyboard"
You should check plugin usage in Ionic Native documentation https://ionicframework.com/docs/native/ to make plugin that actually use working smoothly. If you find a different usage of plugin, then you should update or reinstall the plugin. For example, we are using "cordova-plugin-device" then go to Ionic Native docs and find Device.
Now, reinstall that plugin.
ionic plugin rm cordova-plugin-device
ionic plugin add cordova-plugin-device
npm install --save @ionic-native/device
3. Copy Folders and Files from Old Ionic 2 to Ionic 3 app
Not all folders should copy to new Ionic 3 app. Here's the list of folders and files that may copies.
- resources
- src/assets
- src/pages
- src/providers
- src/themes
- config.xml
- src/app/pipes
- src/assets
- src/pages
- src/providers
- src/themes
- config.xml
- src/app/pipes
And also you can copy your modules, directives or services folder and files.
4. Modify Main Module and Component
Open files "src/app/app.module.ts" from both old Ionic 2 and new Ionic 3 app. Copies all pages, providers, pipes and directives from the old Ionic 2 to the new Ionic 3 App Module. Here's imports example.
import { ApiService } from '../providers/api-service';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { DetailsPage } from '../pages/details/details';
import { OrderByPipe } from './pipes/order-by';
Declare that imported pages to "@NgModule" declarations and entryComponents. Declare pipes and directives in "@NgModule" declarations. Declare providers in "@NgModule" providers.
If you are using Http module for accessing REST API, add this import.
import { HttpModule } from '@angular/http';
Then add in "@NgModule" imports after BrowserModule.
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp, {
backButtonText: '',
iconMode: 'ios',
tabsPlacement: 'top',
menuType: 'overlay',
}),
],
If you are using Ionic Native plugins, add the import like this.
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Device } from '@ionic-native/device';
Then declare in "@NgModule" providers.
providers: [
StatusBar,
SplashScreen,
InAppBrowser,
Device,
{provide: ErrorHandler, useClass: IonicErrorHandler},
ApiService
]
Otherwise, you will face this errors on the browser console log.
ERROR Error: Uncaught (in promise): Error: No provider for Device!
Error
at Error (native)
at g (file:///android_asset/www/build/polyfills.js:3:7133)
at injectionError (file:///android_asset/www/build/main.js:1511:86)
at noProviderError (file:///android_asset/www/build/main.js:1549:12)
at ReflectiveInjector_._throwOrNull (file:///android_asset/www/build/main.js:3051:19)
at ReflectiveInjector_._getByKeyDefault (file:///android_asset/www/build/main.js:3090:25)
at ReflectiveInjector_._getByKey (file:///android_asset/www/build/main.js:3022:25)
at ReflectiveInjector_.get (file:///android_asset/www/build/main.js:2891:21)
at NgModuleInjector.get (file:///android_asset/www/build/main.js:3856:52)
at resolveDep (file:///android_asset/www/build/main.js:11260:45)
at createClass (file:///android_asset/www/build/main.js:11128:32)
at createDirectiveInstance (file:///android_asset/www/build/main.js:10954:37)
at createViewNodes (file:///android_asset/www/build/main.js:12303:49)
at createRootView (file:///android_asset/www/build/main.js:12208:5)
at Object.createProdRootView [as createRootView] (file:///android_asset/www/build/main.js:12786:12) {originalStack: "Error: Uncaught (in promise): Error: No provider f…:///android_asset/www/build/polyfills.js:3:16210)", zoneAwareStack: "Error: Uncaught (in promise): Error: No provider f…:///android_asset/www/build/polyfills.js:3:16210)", rejection: Error: No provider for Device!, promise: t, zone: n…}
That example of error because of Device not declare in "@NgModule" providers.
Next, for "app.component.ts" copy all codes from previous Ionic 2 "app.component.ts". Modify import for Ionic Native to be single import for each other.
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { InAppBrowser } from '@ionic-native/in-app-browser';
Make all modules and plugin injected in the constructor.
constructor(public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
private iab: InAppBrowser,
public apiService: ApiService) {}
Change the calls of modules and plugin which have "@Angular" module installed except for plugin that not have like FCM plugin.
Previously:
StatusBar.styleDefault();
Splashscreen.hide();
Now become:
this.statusBar.styleDefault();
this.splashScreen.hide();
FCM plugin or another plugin that not have "@angular" module treat same as previous Ionic 2.
Finally, we have to add or remove/add platform before running on devices.
ionic platform rm android
ionic platform add android
ionic platform rm ios
ionic platform add ios
Now, we can run directly on the device.
ionic run android
For some Ionic 2 project will use different approach depends on how many plugins or modules that used.
Thanks.