Looking for some clarity and knowledge as I navigate through this code.
I have an AuthService
that checks the values in the localStorage
for a specific key. This observable then uses .next
to send the value back. In the Guard component, I reference this service and everything seems to be working fine. However, I've noticed that there is no redirect to the login page in the guard, so when authorization fails, the page just goes blank.
Below is the code snippet:
isLoggedIn(): Observable<boolean> {
return new Observable((o) => {
try {
const cda = JSON.parse(localStorage.getItem('cda'));
if (cda && cda.token) {
console.log('Yes logged in');
o.next(true);
} else {
console.log('Not logged in');
o.next(false);
}
} catch (e) {
console.log('Catch - Not logged in');
o.next(false);
}
});
}
export class GuardGuard implements CanActivate {
constructor(
public auth: AuthService,
public router: Router,
) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.auth.isLoggedIn();
}
}
How can I convert the Observable
from the AuthService
so that I can implement something like this:
if (!isLoggedIn) {
this.router.navigateByUrl('/login');
}