Advertisement

Latest Post

Friday, 22 September 2017

Login Functionality Using Ionic Framework With Angular 4

Creating new Ionic app I am creating new app with sidemenu and using Ionic generator command to create 2 pages and 1 service.

ionic start myApp sidemenu 
cd myApp 
ionic g page signup 
ionic g page login 
ionic g provider auth.service

 We need to focus inside the src/app/app.module.ts. So open the file and replace everything with below code.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule} from 'ionic-angular';
import { AuthService } from '../Services/auth.services';
import { HttpModule } from '@angular/http';

import { MyApp } from './app.component';
import { WelcomePage } from '../pages/welcome/welcome';
import { LoginPage } from '../pages/login/login';
import { SignupPage } from '../pages/signup/signup';
import { HomePage } from '../pages/home/home';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';



@NgModule({
  declarations: [
    MyApp,
    WelcomePage,
    LoginPage,
    SignupPage,
    HomePage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    WelcomePage,
    LoginPage,
    SignupPage,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    AuthService
    
  ]
})
export class AppModule {}

Now open the src/app/app.component.ts and put rootPage as LoginPage instead of the default home page.

import { Component, ViewChild } from '@angular/core';
import { Nav, Platform ,App,MenuController} from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';
import { AuthService } from '../Services/auth.services';


@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

  rootPage: any = LoginPage;

  pages: Array<{title: string, component: any, icon:string}>;

  constructor(public menuCtrl:MenuController, public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private auth: AuthService) {
   this.initializeApp();    
    if(this.auth.isLogged()===true) 
    {
      this.rootPage=HomePage
     }
     else{
       this.rootPage=LoginPage
     }
  }

  initializeApp() {
    this.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.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    
    this.nav.setRoot(page.component);
  }
}

Now creating the Authentication service with name "auth.services.ts" under services folder

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = 'http://localhost:5288/api/';

@Injectable()
export class AuthService {

  constructor(public http: Http) {}

  login(credentials) {  
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });
  }

  register(data) {
   
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post(apiUrl+'guest/signup', JSON.stringify(data), {headers: headers})
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });
  }

  logout(){
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('X-Auth-Token', localStorage.getItem('token'));

        this.http.post(apiUrl+'logout', {}, {headers: headers})
          .subscribe(res => {
            localStorage.clear();
          }, (err) => {
            reject(err);
          });
    });
  }

  isLogged(){
    if(window.localStorage.getItem('token')){
        return true;
    }else{
        return false;
    }
  }

}


If the auth.service returns that the user is allowed to login we set our root navigation to the HomePage which stands for the logged in area of our app.
Now go to pages and open the src/pages/login/login.ts and replace it with:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController ,ToastController,MenuController} from 'ionic-angular';
import { HomePage } from '../home/home';
import { AuthService } from '../../Services/auth.services';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  loading: any;
  data: any;
  loginData = { username:'', password:'' };
 
  constructor(public navCtrl: NavController,public authService: AuthService, 
    public navParams: NavParams,public loadingCtrl: LoadingController,
    private toastCtrl: ToastController, private menuCtrl:MenuController) 
    {  
     
    }
    
  login(){
    
    this.showLoader();    
    this.authService.login(this.loginData).then((result) => {
      this.loading.dismiss();
      this.data = result;
      localStorage.setItem('token', this.data.access_token);
      this.navCtrl.setRoot(HomePage);
    }, (err) => {
      this.loading.dismiss();
      this.presentToast(err);
    });
  }

  showLoader(){
    this.loading = this.loadingCtrl.create({
        content: 'Authenticating...'
    });

    this.loading.present();
  }

  presentToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom',
      dismissOnPageChange: true
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }  
}

The class is ready, now the view. Now, i am going to create ionic html controls for the login with 2 textbox and a button.
Here is simple code that you need to add in your login page.

<ion-content padding id="login">
    
    <ion-row class="logo-row">       
        <ion-col>
            <h3>Welcome to code-view.com </h3>
        </ion-col>
        
      </ion-row>
    <form (ngSubmit)="login()" #f="ngForm" style="margin-top:50px">
      <ion-list inset>  
          <ion-item>
              <ion-label stacked>Username</ion-label>
              <ion-input [(ngModel)]="loginData.username" name="username" type="text" placeholder="Username" ></ion-input>
          </ion-item>
          <ion-item>
              <ion-label stacked>Password</ion-label>
              <ion-input [(ngModel)]="loginData.password" name="password" type="password" placeholder="Password"></ion-input>
          </ion-item> 
        <button ion-button block type="submit" color="lightsecondary">Login</button>
      </ion-list>
</form>
</ion-content>

you resulting login screen will now look like this:


I am hoping that you are enjoying with this post! Please share with you friends. Thank you!!

Government Jobs