hope I can get some clarification here and learn things as I go.
So I've got an AuthService
which checks localStorage
for a key and the values in it. This is an observable and .next
the value back. In the Guard, I'm referencing this and it works out fine. However, I noticed that I don't have a redirect to login page in the guard so it blanks out the page and that's it when it's not authorized.
Here's my code.
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 do I convert that Observable
from AuthService
so I can do something like
if (!isLoggedIn) {
this.router.navigateByUrl('/login');
}