Angular2 Authguard route to login

1.4k views Asked by At

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;
      });
  }
}
1

There are 1 answers

4
seidme On BEST ANSWER

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;
      });
  }
}