@sdgroup14

Как закрыть роутинг к компоненту Angular 2-5?

суть такова. Делаю Авторизацию. Разобрался как сделать AuthGuard на проверку token.... Все хорошо работает. Но теперь же мне нужно закрыть доступ к странице login... так как я уже авторизован и есть токен.... Пример ниже:

export class AuthService {
  constructor(public jwtHelper: JwtHelperService ) {}
  public isAuthenticated(): boolean {
    // true или false - не стал приводить весь код чтоб не путать, вы поймете
    return true;
  }
}

export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

const routes: Routes = [
  {
    path: '',
    component: AuthComponent,
    children: [ {path: 'login', component: LoginComponent} ]
  },
  {
    path: '',
    component: contentComponent,
    canActivate: [AuthGuard],
    children: [ {path: 'map', component: MapComponent} ]
  },
];


Вообщем проблема случилась такова.... Когда в условия canActivate добавляю условие обратое чтоб если заходишь на /login и есть токен - редиректило на /map но у меня почемуто заходит в цикл и браузер зависает.... Пример кода что я изменил - ниже

// добавил AuthGuard к login

const routes: Routes = [
  {
    path: '',
    component: AuthComponent,
    canActivate: [AuthGuard],
    children: [ {path: 'login', component: LoginComponent} ]
  },
  {
    path: '',
    component: contentComponent,
    canActivate: [AuthGuard],
    children: [ {path: 'map', component: MapComponent} ]
  },
];

//добавил в Guard условие else if

export class AuthGuardService implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {
    if (!this.auth.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    } else if (this.auth.isAuthenticated()){
       this.router.navigate(['/map']);
      return false;
    }
    return true;
  }
}
  • Вопрос задан
  • 130 просмотров
Решения вопроса 1
@instant123
Сделай еще один loginGuard, и в нем пропиши отдельно логику.
export class loginGuard implements CanActivate {
  constructor(public auth: AuthService, public router: Router) {}
  canActivate(): boolean {


    if (!this.auth.isAuthenticated()) {
        return true;
    } else if   {
      this.router.navigate(['/map']);
      return false;
  }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы