Ionic Javascript Framework. Application example and migration from Ionic 3 to Ionic 5
The objective of this article is to reuse the code generated 3 years ago in Ionic 3 (https://github .com/al118345/IONIC-3-example-APP) and partially adapt it to Ionic 5 (https://github.com/al118345/ionic_example_login)I actually found that the project implemented in Ionic 3 does not work with the Node.js version which I have installed in my current development environment. Therefore, I have decided to create two projects, for one part code that you used in version 3 and on the other the equivalent code in ionic 5.
To do this we will create a new project in Ionic 5 and copy and modify certain parts of the code.Application creation
- The project Ionic 3 (https://github .com/al118345/IONIC-3-example-APP) An application has been created using the basic “tabs” template of Ionic Framework and we have customized the splash screen as follows:To perform this task we first have to install Ionic following the instructions in the material. reference:
- Install or check that we have nodeJS version 4 installed
- Install cordova and ionic as npm from the command line using:
npm install -g cordova ionic - Install the app with Ionic View 3
npm install @ionic/cloud-angular --saveTo migrate to version 5 of Ionic View 3
npm uninstall ionic-angular npm install @ionic/angular - Then we can create a new app where we import the old project.
ionic start myApp blank
- The project had the objective of creating a login with the following credentials:
- User :demo
- Password :demo
Ionic 3
From this idea, at the time I executed the following commands from the terminalionic g provider authoService ionic g provider login ionic g provider logoutOnce the new pages have been created, I have generated the user data model (models/user.ts)export class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; this.email = email; } }With the model created, I have modified the service to generate the login. This modification is stored in the providers/autho-service/autho-service.ts file and the most important method is the login, shown at continued:login(credentials): Observable<boolean> { if (credentials.email === null || credentials.password === null) { return Observable.throw("Please insert credentials"); } else { this.logueado = false; return Observable.create(observer => { //nos comunicamos con el servicio web de login //y con el resultado que nos proporcione redirigimos al //hombe o nos quedamos en el login this.comunicaciones.login_Web( credentials.email, credentials.password).subscribe(result => { if (result === true) { // login successful this.currentUser = credentials; //vamos a home observer.next(true); observer.complete(); } else { // login failed this.currentUser = credentials; // Volvemos a pedir la introducción de los datos. observer.next(false); observer.complete(); } }); }); } }To subdivide the communication process of the logging logic, I have created the file providers/comunicaciones/comunicaciones.ts where the login_web method has the post communication method with the web server.//método de comunicación con el servicio web alojado en multimedia.uoc.edu. login_Web(username: string, password: string): Observable<boolean> { //alert(username); const params: URLSearchParams = new URLSearchParams(); params.set('user', username); params.set('passwd', password); return this.http.post( 'http://multimedia.uoc.edu/frontend/auth.php', params) .map((response: Response) => { if (response.json().status.localeCompare('OK') === 0) { return true; } else { return false; } }); }ionic 4 or ionic 5
In the blank project we will execute the following command.
ionic g service services/comunicacionesIn the new version, the resulting modified code would look like this:import { Injectable } from '@angular/core'; import {User} from '../models/user'; @Injectable({ providedIn: 'root' }) export class ComunicacionesService { public user: User; constructor() { try { const currentUser = JSON.parse(localStorage.getItem('currentUser')); } catch (e) { const currentUser = ''; } } login(username: string, password: string): boolean { const xhr = new XMLHttpRequest(); const data = { 'user': username, 'passwd': password }; localStorage.clear(); xhr.open('POST', 'http://multimedia.uoc.edu/frontend/auth.php', false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onload = function() { return xhr.response; // do something with jsonResponse }; xhr.send('user=demo&passwd=demo'); if ( JSON.parse(xhr.responseText).status !== 'OK') { return false; } else { this.user = new User(username, password); localStorage.setItem('currentUser', this.user.to_json() ); return true; } } logout(): void { localStorage.setItem('currentUser', ''); localStorage.removeItem('currentUser'); } }At this moment I have decided to unify both functions and directly create a single file with all the content. I have also used the XMLHttpRequest method to perform communications with the API in http replacement - We add a style to the component tabs with the aim of modifying the default style.
- Modifying the color of the tab background. For this I have modified the file pages/tabs/tabs.scss
.tabs-md .tabbar{ background-color: #9cff00 !important; } - Add an extra option in the tab. For this I have added pages/tabs/tabs.html to the file the following code.
<ion-tab [root]="tab4Root" tabIcon="exit" tabTitle="Logout"></ion-tab>Additionally, I have modified the pages/tabs/tabs.ts file by adding the new page created.tab4Root = LogoutPage; - Create an icon for the Tab. To do this I have modified the pages/tabs/tabs.scss file
.ion-ios-exit,.ion-md-exit{ content: url(../../images/exit.svg); width: 24px; height: 32px; padding: 6px 4px 2px; opacity: 0.9; } - Testing with scss. To generate different tests using the scss compiler I have modified the following files
- pages/home/home.scss: Using a set-notification-text-color method I adapt the color of the text to the background of the object that contains it. Also create a notification class to optimize the code.
//ejemplo de función de scss que modifica el color del texto dependiendo del fondo. @function set-notification-text-color($color) { @if (lightness($color) > 50) { @return #000000; // Lighter backgorund, return dark color } @else { @return #ffffff; // Darker background, return light color } } page-home { //creo las variables con los colores $notification-confirm: hsla(101, 72%, 37%, 1); // Green $notification-warning: #ffc53a; // Yellow $notification-alert: rgb(172, 34, 34); // Red //clase notificacion %notification { border-radius: 10px; display: block; font-size: 1.5em; font-family: sans-serif; padding: 1em 2em; margin: 1em auto; width: 30%; text-align: center; } .notification { @extend %notification; } //genero los diferentes objetos notificacion con un color de la letra adaptado al nombre. .notification-confirm { background: $notification-confirm; color: set-notification-text-color($notification-confirm); } .notification-warning { background: $notification-warning; color: set-notification-text-color($notification-warning); } .notification-alert { background: $notification-alert; color: set-notification-text-color($notification-alert); } } - pages/login/login.scss: In this document I have applied several CSS modifications basic.
page-login { .login-content { background: #56CA96; .logo-row { padding-top: 50px; padding-bottom: 20px; } .login-box { background: #399F8B; padding: 20px 20px 0px 20px; margin-top: 30px; } ion-row { align-items: center; text-align: center; } ion-item { //redonde los text box border-radius: 30px !important; padding-left: 30px !important; font-size: 0.9em; margin-bottom: 10px; border: 1px solid #ffffff; border-bottom: 0px !important; box-shadow: none !important; } .signup-col { margin: 0px 16px 0px 16px; padding-bottom: 20px; } .item-inner { border-bottom-color: #ffffff !important; box-shadow: none !important; } .submit-btn { background: #51CFB1; border-radius: 30px !important; border: 1px solid #ffffff; } .register-btn { color: #ffffff; font-size: 0.8em; } } }
- pages/home/home.scss: Using a set-notification-text-color method I adapt the color of the text to the background of the object that contains it. Also create a notification class to optimize the code.
- Shutdown function The new tab option allows the user to disconnect, but is not correctly implemented. Currently, the application does not take into account which user is logged in, and its logic is only based on redirecting the user to the login page. The code is available in pages/logout/logout.ts:
ionViewDidLoad() { this.navCtrl.push('LoginPage'); location.assign('/'); }
- Modifying the color of the tab background. For this I have modified the file pages/tabs/tabs.scss
Github codes
The exposed codes can be consulted at the following addressesIf you need help, the following explanatory video is available: https://www.youtube.com/watch?v=CUsklt966rA.