【发布时间】:2021-09-11 06:24:25
【问题描述】:
我的 canActivate 守卫是这样工作的:如果当前(fire auth)用户有一个用户配置文件,那么他可以访问路由。否则,我会将他引导至个人资料创建页面。
这很好用,除非我刷新页面!
后卫:
export class UserProfileGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.userProfile) {
return true;
}
this.router.navigate(['user/createprofile']).then();
return false;
}
}
认证服务:
export class AuthService implements OnDestroy {
public userProfile: UserProfile | null = null;
private subscription: Subscription | undefined;
constructor(public fire: AngularFireAuth, private httpService: HttpHandlerService) {
this.subscription = this.fire.authState.subscribe(fireAuthUser => {
if (fireAuthUser) {
this.httpService.getMyProfile().subscribe((profile: UserProfile) => {
this.userProfile = profile;
})
}
});
}
}
因此,如果我在受保护的路线上并刷新页面,我总是会被发送到个人资料创建页面,即使个人资料存在。
我担心在 Auth Service 尚未获取配置文件的时候,在刷新的情况下,Guard 检查太早。
你能帮我解决这个问题吗?
提前致谢!
【问题讨论】:
标签: angular firebase angular-guards angular12