Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
Angular2: Trigger current route guards - handle logout action

I'm using JWT to authenticate users. Part of routs in my angular2 app are protected by CanActivate Guard that will redirect to login page if user is not logged in. Now I'm implementing logout button and would like to redirect to login page. I want to redirect only if current route should not be visible to non logged-in users (e.g. account page). If user is for example in home page I don't want to redirect to login page.

It would be perfect if I could just check if current route have guard and trigger this guard if it exist. It is possible to do this ?

Guard:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.loginService.getCurrentUserName()) {
        // logged in so return true
        return true;
    }
    // not logged in so redirect to login page with the return url
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
}
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

For all route guard needed pages, you can have a specific route path (like '/account/..' and you can check for whether the route guard page is logged in or not

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    this.checkRouteNaviation(this.route.url);
}

public checkRouteNaviation(url) {
    if(url.includes('account') && !this.loginService.getCurrentUserName()) {
        // when url is of guard url and not logged in, redirect to login page with the return url
        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
        return false;
    }
    return true;
}

Hope it helps

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda