angularangular2-routingangular2-router3

Angular2 Authguard route to login


if user who don't login, want to go some secure root for example "/items" authguard return false and dont navigate "/login".

export const APP_ROUTES: Routes = [
  {path: '', component: PublicComponent, children: PUBLIC_ROUTES},
  {
    path: '',
    component: SecureComponent,
    resolve: {user: UserResolver},
    canActivate: [AuthGuard],
    children: SECURE_ROUTES
  },
  {path: '', redirectTo: '/login', pathMatch: 'full'}
];

AuthGuard Code:

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private userService: UserService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
    let url: string = state.url;
    return this.checkLogin(url);
  }

  checkLogin(url: string): Observable<boolean> {
    this.userService.redirectUrl = url;
    return this.userService.getPrincipal()
      .map(user => {
        if(user)
          return true;

        return false;
      });
  }
}

Solution

  • Inject Router, and redirect to login page if user is not logged in as follows:

    @Injectable()
    export class AuthGuard implements CanActivate {
    
      constructor(private userService: UserService, private router: Router) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean{
        let url: string = state.url;
        return this.checkLogin(url);
      }
    
      checkLogin(url: string): Observable<boolean> {
        this.userService.redirectUrl = url;
        return this.userService.getPrincipal()
          .map(user => {
            if(user)
              return true;
    
            this.router.navigate(['login']);
            return false;
          });
      }
    }