Search code examples
angularangular-routingangular-route-guards

Angular- Route Guard always redirects to home page before navigation


I am trying to implement a route guard on my website. It checks for the token and then returns true or false. It is supposed to redirect if it returns false. However, when it is supposed to navigate it firstly goes to "/" route before going to the desired route.

Eg.

Current Behavior

Check for token.

Token returns false.

Redirects to "/"

Then navigates to "/me/courses"

Expected Behavior

Check for token.

Token returns false

Navigates to "/me/courses"

This is my route guard

  canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    var API_PATH = "auth/user/"
    var isAuthenticated = this.authService.isLoggedIn()

    if(!isAuthenticated) {
      return true
    }

    this.router.navigateByUrl("/me/courses")
    return false
  }

This is my code to check for the token

  loggedIn(autoFetchUserDetails = false) {
        if (autoFetchUserDetails) {
        this.fetchUserDetails();
    }
}

  isLoggedIn() {
      const token = this.globalService.getAuthToken();
      if (token) {
          if (!this.isAuth) {
            this.loggedIn(true);
          }
          return true;
      } else {
          if (this.isAuth) {
            this.logOut();
          }
          return false;
      }
    }

  fetchUserDetails() {
      const API_PATH = 'auth/user/';
      const SELF = this;
      this.api.getUrl(API_PATH).subscribe(
        data => {
          this.isAuth = true;
          this.user = data;
        },
        err => {
          this.globalService.deleteCookie(this.globalService.authStorageKey);
          this.logOut()
        }
      );
  }


Solution

  • The problem you have is that you are returning false. This tells the system to block the navigation completely.

    If you want it to go to a different URL, such as "/me/courses", then you need to return a UrlTree object from the Route Guard, instead of false.

      canActivate(): boolean | UrlTree {
        var API_PATH = "auth/user/"
        var isAuthenticated = this.authService.isLoggedIn()
    
        if(!isAuthenticated) {
          return true
        }
    
        const tree: UrlTree = this.router.parseUrl("/me/courses");
        return tree;
      }