firebaseionic-frameworkfirebase-authenticationionic4ionic-storage

In ionic how to set storage to login information so when restarting the app takes directly to the home page


I am using the ionic framework. How do I set storage to login information so if the app restart the user can go to the home page when filling the login information again and again.

import * as firebase from 'firebase/app';
import { Storage } from '@ionic/storage';


@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {


  constructor(public storage: Storage) {}

    loginUser(value){
     firebase.auth().signInWithEmailAndPassword(value.email, value.password)
      .then(() => {
        console.log('Log In Successful, UID: ' + value.uid + 'Email: ' + 
       value.email);
         this.storage.set('Email', value.email);
         this.storage.set('Password', value.password);
      })
      }
    }

Solution

  • Ref. My github Url

    authentication.service.ts

    import { Injectable } from '@angular/core';
    import { Router } from '@angular/router';
    import { Storage } from '@ionic/storage';
    import { ToastController, Platform } from '@ionic/angular';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthenticationService {
    
      authState = new BehaviorSubject(false);
    
      constructor(
        private router: Router,
        private storage: Storage,
        private platform: Platform,
        public toastController: ToastController
      ) {
        this.platform.ready().then(() => {
          this.ifLoggedIn();
        });
      }
    
    
      ifLoggedIn() {
        this.storage.get('USER_INFO').then((response) => {
          if (response) {
            this.authState.next(true);
          }
        });
      }
    
    
      login() {
        var dummy_response = {
          user_id: 'manzoor.alam@thinktac.com',
          user_name: 'manzoor'
        };
        this.storage.set('USER_INFO', dummy_response).then((response) => {
          this.router.navigate(['dashboard']);
          this.authState.next(true);
        });
      }
    
      logout() {
        this.storage.remove('USER_INFO').then(() => {
          this.router.navigate(['login']);
          this.authState.next(false);
        });
      }
    
      isAuthenticated() {
        return this.authState.value;
      }
    }
    

    In auth-guard.service.ts

    import { Injectable } from '@angular/core';
    import { AuthenticationService } from './authentication.service';
    import { CanActivate } from '@angular/router';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthGuardService implements CanActivate {
    
      constructor( public authenticationService: AuthenticationService) { }
    
      canActivate(): boolean {
        return this.authenticationService.isAuthenticated();
      }
    }
    

    App.component.ts file

    import { Component } from '@angular/core';
    
    import { Platform } from '@ionic/angular';
    import { SplashScreen } from '@ionic-native/splash-screen/ngx';
    import { StatusBar } from '@ionic-native/status-bar/ngx';
    import { AuthenticationService } from './services/Authentication.service';
    import { Router } from '@angular/router';
    
    
    @Component({
      selector: 'app-root',
      templateUrl: 'app.component.html'
    })
    export class AppComponent {
      constructor(
        private platform: Platform,
        private splashScreen: SplashScreen,
        private statusBar: StatusBar,
        private router: Router,
    
        private authenticationService: AuthenticationService
    
      ) {
        this.initializeApp();
      }
    
      initializeApp() {
        this.platform.ready().then(() => {
          this.statusBar.styleDefault();
          this.splashScreen.hide();
    
          this.authenticationService.authState.subscribe(state => {
            if (state) {
              this.router.navigate(['dashboard']);
            } else {
              this.router.navigate(['login']);
            }
          });
    
        });
    
      }
    }
    

    In app-routing.module.ts

    import { NgModule } from '@angular/core';
    import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
    import { AuthGuardService } from './services/auth-guard.service';
    
    
    const routes: Routes = [
      // { path: '', redirectTo: 'home', pathMatch: 'full' },
      // { path: 'home', loadChildren: './home/home.module#HomePageModule' },
      // { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      // { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardPageModule' },
    
      { path: '', redirectTo: 'login', pathMatch: 'full' },
      { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
      {
        path: 'dashboard',
        loadChildren: './dashboard/dashboard.module#DashboardPageModule',
        canActivate: [AuthGuardService]
        // Here canActivate is a method inside the AuthGuardService which return boolen type values
      }
    ];
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    Please Ref. My github url more details github Url