Angular在带有Firebase的身份验证系统中始终返回undefined或null

时间:2019-02-25 08:26:05

标签: javascript angular firebase firebase-authentication angularfire2

我正在email and password中使用firebase构建身份验证系统,登录和注销都可以作为响应console.log(authState)正常工作,但是 angular guard 总是返回方法isLoggedIn()null,我不知道为什么?!在构造函数中,我已使用userDetails值定义了它:

仅用于auth.service构造函数的代码:

  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;
        console.log(this.userDetails); // I get a response from this on the login page with user details ( user is logged in )
      }
    )

  }

该方法的代码:

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

整个服务的代码(auth.service.ts):

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;
        console.log(this.userDetails); 
      }
    )

  }

  async siginInRegular(username: string, password: string) {
    // const credentials = this.af.auth.email
    const results = await this.af.auth.signInWithEmailAndPassword(username, password).then(
      results => {
        this.navCtrl.navigateForward('/home');
        this.statusMessage.message(`Welcome ${results.user.email}`);
      }
    );

  }

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

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


  constructor(
    private auth: AuthService
  ) {
    console.log(auth.isLoggedIn());

  }

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


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

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

1 个答案:

答案 0 :(得分:2)

您的代码中可能会有一场竞赛。当您从警卫人员那里调用AuthService时,this.userDetails尚未“就绪”。

您可以做的是,在接受canActivate的情况下,在Observable<boolean> | Promise<boolean> | boolean方法中返回一个promise / observable。

一个基本的例子可能是这样:

  1. 添加一种方法来获取您的身份验证服务中的身份验证状态:

     get authState(): Observable<any> {
       return this.af.authState;
     }
    
  2. 在您的canActivate()方法中使用它:

    canActivate(): Observable<boolean> {
      return this.authService.authState()
        .pipe(
             map(authState => !!authState),
             tap(auth => !auth ? console.log('Access Denied!') : true),
             take(1)
         );
    }