首页 > 解决方案 > 无法检查用户是否已登录 Firebase + Angular

问题描述

目前我登录了我的用户,然后我想实现一些路由守卫,以便在用户未登录时无法访问它们。

所以这是我的后卫。

    import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from '@angular/fire/auth';
@Injectable({
  providedIn: 'root'
})
export class AuthguardGuard implements CanActivate {
constructor(public af: AngularFireAuth){

}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
      var user = this.af.auth().currentUser;

      if (user) {
        return true;
      } else {
        return false;
      }
  }

}

问题是--->var user = this.af.auth().currentUser;给出了一个错误

Cannot invoke an expression whose type lacks a call signature. Type 'Auth' has no compatible call signatures.ts(2349)
(property) AngularFireAuth.auth: firebase.auth.Auth

oO 我应该如何检查用户是否已登录?我不想为此使用 localSTorage。

标签: angularfirebasefirebase-authenticationangularfire2

解决方案


我最终使用了以下 canActivate

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    return this.auth.authState.pipe(map(User => {
      if (User) {
        return true;
      } else {
        this.router.navigate(['/login']);
        return false;
      }
    }));
  }

推荐阅读