我使用Google登录实施了Firebase身份验证(效果很好)。但是在成功登录后,我无法导航到我的家庭组件。我该如何实现?
我已执行检查以查看是否已登录,然后导航到“主页”。它检测到我已登录,但没有导航到我的家庭组件。
const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'login' },
{ path: 'login', component: LoginSignupComponent },
{ path: 'hc-home', component: HcHomeComponent, children: [
{ path: 'calender', component: CalenderComponent},
{ path: 'attendance', component: AttendanceComponent}
], canActivate: [CanActivateGuard]}
];
user$: Observable<User>;
constructor(private router: Router,
private afs: AngularFirestore,
private afAuth: AngularFireAuth) {
this.user$ = this.afAuth.authState.pipe(
switchMap(user => {
if (user) {
return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
} else {
return of(null);
}
})
);
}
async googleSignIn() {
const provider = new auth.GoogleAuthProvider();
const credential = await this.afAuth.auth.signInWithPopup(provider);
return this.updateUserData(credential.user);
}
async signOut() {
await this.afAuth.auth.signOut();
return this.router.navigateByUrl('login');
}
private updateUserData(user) {
const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);
const data = {
displayName: user.displayName,
email: user.email,
photoURL: user.photoURL,
uid: user.uid
};
return userRef.set(data, { merge: true });
}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.user$.pipe(
take(1),
map(user => !!user),
tap(loggedIn => {
console.log(loggedIn);
if (loggedIn === true) {
console.log('inside true function');
this.router.navigate(['/hc-home']);
}
if (!loggedIn) {
console.log('Access Denied');
this.router.navigateByUrl('login');
}
})
);
我的预期结果是成功登录后导航到主页(运行正常),但由于某种原因,它提示我已登录并进行了Firebase身份验证,并且控制台确认了这一点,但我仍然停留在登录页面上。没有任何错误消息。
答案 0 :(得分:0)
在身份验证防护中,如果允许用户导航到指定的URL,则需要返回true
。当前,您正在尝试导航到url,但实际上并没有告诉角度以允许用户导航到该URL。同样,当允许用户导航到家时,您也无需尝试导航到家。您已在路线hc-home
上安装了防护装置,因此角度允许的话就已经知道要在那儿进行路由。将您的代码更改为:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.user$.pipe(
take(1),
map(loggedIn => {
if (loggedIn) {
return true;
}
this.router.navigateByUrl('login');
return false;
}
})
);
而且,angularfire还具有自己的authguard插件,您实际上不需要编写自己的authguard:https://github.com/angular/angularfire2/blob/master/docs/auth/router-guards.md就像扔在那里的另一个选择一样。