Firebase:保持用户登录角度7

问题描述 投票:0回答:1

我在身份验证系统中使用firebase和angularfire2!

问题是刷新后用户需要再次登录!我需要避免这个问题所以我发现firebase通过使用authState给了我这个选项

但还是不行!

这是authService的代码:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/internal/observable';
import { NavController } from '@ionic/angular';
import { ToastMessagesService } from './toast-messages.service';
import * as firebase from 'firebase';

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

  public user: Observable<firebase.User>;
  public userDetails: firebase.User = null;


  constructor(
    private af: AngularFireAuth,
    private navCtrl: NavController,
    private statusMessage: ToastMessagesService
  ) {

    this.user = af.authState;

    this.user.subscribe(
      user => this.userDetails = user
    )


  }

  async siginInRegular(username: string, password: string) {
    try {

      // const credentials = this.af.auth.email
      return await this.af.auth.signInWithEmailAndPassword(username, password).then(
        user => {
          if (user) {
            this.navCtrl.navigateForward('/home');
            this.statusMessage.message(`Welcome ${user.user.email}`);
          }
        },
        err => {
          console.log(err);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  async register(username: string, password: string) {
    try {
      return await this.af.auth.createUserWithEmailAndPassword(username, password).then(
        user => {
          this.navCtrl.navigateForward('/profile');
          this.statusMessage.message(`Welcome ${user.user.email}`);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  signOut() {
    return this.af.auth.signOut();
  }

  isLoggedIn(): boolean {
    return (this.userDetails != null) ? true : false;
  }


}

守卫代码:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { NavController } from '@ionic/angular';
import { AngularFireAuth } from 'angularfire2/auth';

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



  constructor(
    private auth: AuthService,
    private navCtrl: NavController,
    private af: AngularFireAuth
  ) {

  }

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


    if (this.auth.isLoggedIn()) {
      return true
    }

    console.log('Access denied!');
    return false;

  }
}
javascript angular firebase firebase-authentication angularfire2
1个回答
0
投票

Firebase实际上会在您重新加载页面时自动为用户签名。但由于您对登录的处理仅在then()块中,因此只有在您明确签名时才会发生。

要解决此问题,您需要使用onAuthState中显示的get the currently signed in user侦听器:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

then()处理程序不同,每次用户的身份验证状态更改时,都会调用此onAuthStateChanged处理程序,包括重新加载页面时。

由于您使用的是AngularFire2,您还可以使用af.auth.subscribe,如下所示:How to get the firebase.User in AngularFire2

© www.soinside.com 2019 - 2024. All rights reserved.