大家好,我正在开发一个带有 angular 和 firebase 的共享应用程序,我遇到了一个问题,我有 1. 以前从未遇到过 2. 尝试了堆栈溢出的解决方案,但无济于事。我正在我的应用程序中实施身份验证保护,以便某些页面只能由经过身份验证的用户查看。 这是我的登录指令代码:
import { Directive, HostListener } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import * as firebase from 'firebase/app';
@Directive({
selector: '[appGoogleSignin]',
})
export class GoogleSigninDirective {
constructor(private afAuth: AngularFireAuth) {}
@HostListener('click')
onclick() {
this.afAuth
.setPersistence(firebase.default.auth.Auth.Persistence.LOCAL)
.then(() => {
this.afAuth.signInWithPopup(
new firebase.default.auth.GoogleAuthProvider()
);
});
}
}
这是我的 authguard 代码:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { SnackService } from '../services/snack.service';
@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private afAuth: AngularFireAuth, private snack: SnackService) {}
async canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Promise<boolean> {
const user = await this.afAuth.currentUser;
const isLoggedIn = !!user;
if (!isLoggedIn) {
this.snack.authError();
}
return isLoggedIn;
}
}
这是我对身份验证保护的实现:
path: 'upload',
loadChildren: () =>
import('./upload/upload.module').then((m) => m.UploadModule),
canActivate: [AuthGuard],
},
我尝试了多种解决堆栈溢出的方法,包括将持久性状态设置为会话和本地。没有一个对我有用。
答案 0 :(得分:0)
加载页面时,this.afAuth.currentUser
值会异步刷新。因此,当您的代码访问 this.afAuth.currentUser
时,它可能尚未设置。
不是同步访问 this.afAuth.currentUser
值,而是观察 auth.user
流以确保您始终对最新的身份验证状态做出反应。另请参阅 Getting started with Firebase Authentication 中的第一个代码示例。