0

I am trying to check if a user is authorized and if not direct him/her to login page. I actually managed to do that but i am having an hard time how the mechanism works. please see below code.

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let fus: FakeUserService  = new FakeUserService();
    if(!fus.authorization()){
      this.router.navigate(['login']);
      return false; // Code works even this line is commented out. The user is redirected to the login page.
    }
    return true;
  }

The point i don`t understand is how router.navigate works in this scenario. Does user go to the intended page and navigated back to login when i comment out "return false"?. Or "router.navigate" function overrides all the routing commands? I am kind of confused..

rematnarab
  • 1,277
  • 4
  • 22
  • 42

1 Answers1

0
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";

@Injectable()
export class AuthGuard implements CanActivate{


  constructor(protected router: Router)
  {

  }

    canActivate(route: ActivatedRouteSnapshot,
                state: RouterStateSnapshot):Observable<boolean> | boolean{
      console.log("In Can Activate AuthGuard");
      if(route.params['key'] == "X"){
        return true;
      }
      this.router.navigate(['/home',{message:"Not Authorised"}]);
      return false;
    }
}

Route

  { path: 'guardcheck', component:  CheckComponent , canActivate: [AuthGuard]},

In the above example we return true when we want the user to proceed with the route on which the guard is placed and if not we navigate to the error page using router navigate and return false .

This false returned is for the guard to know that the condition failed .

A working example

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86