VIK6Galado
VIK6Galado

Reputation: 680

Angular router.navigate() is not working after being redirected using AuthGaurd

I'm implementing routing in my Angular application with route guard

const appRoutes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'dashboard', canActivate: [AuthGuard], component: DashboardComponent }
];

auth.gaurd.ts

import { Injectable } from '@angular/core';
import { ActivatedRoute, ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';


@Injectable({
    providedIn: 'root'
})
export class AuthGuard implements CanActivate {

    constructor(private authService: AuthService, private router: Router, private route: ActivatedRoute) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if (this.authService.isAuthenticated()) {
            return true;
        } else {
            this.router.navigate(['/']);
            return false;
        }
    }
}

login.component.ts (funtion that responds once click on login button)

public onSubmit(loginForm): void {
    this.loginFailed = false;
    this.submitted = true;

    if (loginForm.invalid) {
      return;
    }

    if (this.authService.login(this.userName, this.password)) {
      console.log('ABLE TO CONSOLE THIS'); // THIS LINE IS EXECUTING 
      this.router.navigate(['/dashboard']);
    } else {
      this.loginFailed = true;
    }
  }

At first, if I'm not authenticated and I try to navigate directly to /dashboard, I'm being navigated back to '/' route which is right behavior. But, when I try to login again (without refreshing page) with correct credentials I'm not able to login and cannot navigate to /dashboard anymore.

Could anyone please let me know what I'm missing here?

Upvotes: 1

Views: 3131

Answers (2)

mitschmidt
mitschmidt

Reputation: 516

The cleanest and suggested way to handle a guard redirect since Angular v7 would be to return a URLTree inside your guard, instead of imperatively navigating and returning false afterwards. This helps to prevent other navigation related bugs.

Your code might look something like this afterwards:

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        if (this.authService.isAuthenticated()) {
            return true;
        } else {
            return this.router.parseUrl('/');
        }
    }

You could read more about that here: https://juristr.com/blog/2018/11/better-route-guard-redirects/

Upvotes: 0

prashant Jha
prashant Jha

Reputation: 245

The problem is you are using, canActivate, which only prevents the unauthorized access of your route but does not prevent to load the module. so your module is already being loaded thats why its not working withought , refresh .

I will suggest you to use canLoad with canActive

Upvotes: 3

Related Questions