My canActivate guard works like this: if the current (fire auth) user has a user profile, then he can access the route. Otherwise, I route him to the profile creation page.
This works perfectly fine, unless I refresh the page!
Guard:
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;
}
}
Auth Service:
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;
})
}
});
}
}
So if I'm on a protected route and refresh the page, I'm always sent to the profile creation page, even if a profile exists.
I fear that the guard checks too early in case of refresh, in a time in which the profile is not yet fetched by the Auth Service.
Can you please give me some assistance on how to solve this?
Thanks in advance!