I am facing a problem with my app's routing functionality. When the user logs in with their Google email, I want the app to route to the home page: "". Everything seems to work fine except for the canActivate routeGuard. During the AuthLogin function, this.authService.isLoggedIn
returns false after attempting to navigate to "". However, if I try to go to "" immediately after logging in, it works because this.authService.isLoggedIn
shows true in the console.log. It appears that the canActivate function needs to wait until this.authService.isLoggedIn
is updated. Do you have any ideas on how to resolve this issue?
Here are some relevant sections of code:
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 },
// Redirect to home if path does not match any defined routes
{ path: "**", redirectTo: "" },
];
auth.service:
// Returns true when user is logged 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;
}
}