在ionic中如何设置存储以登录信息,以便在重新启动应用程序时直接进入主页

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

我正在使用离子框架。如何设置存储登录信息,使应用重启后,用户可以在一次又一次填写登录信息时进入首页。

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);
      })
      }
    }

使用路由器卫士。

Guard 只是一个 Angular 服务 - 或可注入的 - 以可维护的方式控制路由器的行为。让我们用 CLI 生成它:

ionic generate guard guards/login

守卫包含一个特殊的 canActivate 方法,我们需要实现该方法,该方法必须 return 或解析为布尔值。因为 Ionic Storage 是 Promise-based,我们可以把它做成一个异步函数。它的工作是从设备存储中读取 loginComplete 值。如果为 true 则允许路由处于活动状态,但如果为 false 它将阻止路由并重定向到登录。

// ...omitted
import { Storage } from '@ionic/storage';

@Injectable({
  providedIn: 'root'
})
export class LoginGuard implements CanActivate {

  constructor(private storage: Storage, private router: Router) {}

  async canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {

    const isComplete = await this.storage.get('loginComplete');

    if (!isComplete) {
      this.router.navigateByUrl('/login');
    }

    return isComplete;
  }
}

应用保护

app-routing.module

import { Routes, RouterModule } from '@angular/router';
import { LoginGuard } from './guards/login.guard';

const routes: Routes = [
  {
    path: '',
    loadChildren: './tabs/tabs.module#TabsPageModule',
    canActivate: [LoginGuard] // <-- apply here 
  },
  {
    path: 'login',
    loadChildren: './login/login.module#LoginPageModule'
  }
];
@NgModule(...)
export class AppRoutingModule {}

登录页面

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);
           this.storage.set('loginComplete', true);
      })
      }
    }

希望对你有帮助:)

参考 url:AngularFirebase

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;
  }
}

在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 文件

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']);
        }
      });

    });

  }
}

在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 { }

请参考。我的githuburl更多详情github Url