Search code examples
angularangular-routingangular-router

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?


Solution

  • 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