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

时间:2019-07-10 10:27:54

标签: firebase ionic-framework firebase-authentication ionic4 ionic-storage

我正在使用离子骨架。如何设置存储登录信息,以便在应用重新启动时,用户可以在一次又一次填写登录信息时转到主页。

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

2 个答案:

答案 0 :(得分:0)

使用Router Guard。

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

ionic generate guard guards/login

该防护包含一个特殊的canActivate方法,我们必须实现该方法,该方法必须返回或解析为布尔值。由于Ionic Storage基于Promise,因此我们可以使其成为异步函数。它的工作是从设备存储中读取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);
      })
      }
    }

希望它对您有帮助:)

引用网址:AngularFirebase

答案 1 :(得分:0)

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

请参考我的github网址的更多详细信息github Url