我希望我的应用程序在用户使用他们的谷歌电子邮件登录时路由到家:“”。除了 canActivate routeGuard 之外,一切正常。this.authService.isLoggedIn
在 AuthLogin 函数期间尝试导航到“”后返回 false。登录后,routeguard 路由到“login”而不是“”,如果我尝试直接转到“”,它会起作用,因为this.authService.isLoggedIn
在 console.log 中显示为 true。所以似乎 canActivate 需要一种方法来等到this.authService.isLoggedIn
更新,有什么想法吗?
应用程序路由模块:
import { AuthGuard } from "./shared/guard/auth.guard";
const routes: Routes = [
{ path: "", component: HomeComponent, canActivate: [AuthGuard] },
{ path: "login", component: LoginComponent },
{ path: "results", component: ResultsComponent },
{ path: "profile", component: ProfileComponent },
// otherwise redirect to home
{ path: "**", redirectTo: "" },
];
身份验证服务:
// Returns true when user is looged in and email is verified
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem("user"));
return user !== null && user.emailVerified !== false ? true : false;
}
googleLogin() {
return this.AuthLogin(new firebase.auth.GoogleAuthProvider());
}
async AuthLogin(provider: firebase.auth.AuthProvider) {
try {
const result = await this.afAuth.auth.signInWithPopup(provider);
this.SetUserData(result.user);
this.router.navigate([""]);
} catch (error) {
window.alert(error);
}
}
SetUserData(user) {
const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`);
const userData: User = {
uid: user.uid,
email: user.email,
displayName: user.displayName,
photoURL: user.photoURL,
emailVerified: user.emailVerified,
};
return userRef.set(userData, {
merge: true,
});
}
auth.guard:
import { AuthService } from "src/app/services/auth/auth.service";
@Injectable({
providedIn: "root",
})
export class AuthGuard implements CanActivate {
constructor(public authService: AuthService, public router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
console.log(this.authService.isLoggedIn);
if (this.authService.isLoggedIn !== true) {
this.router.navigate(["login"]);
}
return true;
}
}