S
S
sdgroup142018-03-21 15:14:20
Angular
sdgroup14, 2018-03-21 15:14:20

How to close routing to Angular 2-5 component?

the essence is this. I do Authorization. I figured out how to make AuthGuard to check token .... Everything works well. But now I need to close access to the login page... since I'm already logged in and have a token.... Example below:

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} ]
  },
];

In general, the problem happened is this .... When I add the reverse condition to the canActivate conditions so that if you go to /login and there is a token, it redirects to /map, but for some reason it goes into a loop and the browser freezes .... An example of the code that I changed is below
// добавил 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;
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
instant123, 2018-03-25
@sdgroup14

Make another loginGuard, and write logic in it separately.

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question