1

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');
}
j3ff
  • 5,719
  • 8
  • 38
  • 51
newbie
  • 21
  • 1
  • 3

1 Answers1

2

Working demo in this StackBlitz Link

**

EDIT [ If you do not want to use third variable ]

service.ts

@Injectable()
export class DataService {
   constructor() { }
   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);
     }
   });  
 }
}

your-guard.ts

export class RouterGuard implements CanActivate {
constructor(private dService : DataService,
          private router: Router){}
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
       return this.dService.isLoggedIn().pipe(
        map(value =>  {
          if(!value) this.router.navigate(['/login'])
          return value;
        })
      )
    }
}

**

---- EDIT COMPLETE ----

In your guard serve you need...

canActivate(next: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<boolean> {

      return this.auth.getIsUserLoggedIn() ? true : this.router.navigateByUrl('/login');
}

and in your authSevice you need...

isLoggedin: boolean;

isLoggedIn(): Observable<boolean> {
  return new Observable((o) => {
    try {
     const cda = JSON.parse(localStorage.getItem('cda'));
     if (cda && cda.token) {
       console.log('Yes logged in');
       this.isloggedin = true;
       o.next(true);
     } else {
       console.log('Not logged in');
       this.isloggedin = true;
       o.next(false);
     }
    } catch (e) {
     console.log('Catch - Not logged in');
     o.next(false);
   }
 });

}

 getIsUserLoggedIn(){
     return this.isloggedin;
 }

Basically, return true or false and based on that you can redirect user.

Developer
  • 3,309
  • 2
  • 19
  • 23