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

332
Visualizações
Angular4 Routing: Force Navigation By Bypassing Route Guard

When my users have dirty changes on a screen, I have a route guard to prompt them to save or discard when they try to navigate away.

However, if I am logging them out due to inactivity, I want to force navigation and bypass the route guard (by discarding their changes), in order to ensure that their screen is blanked.

How can I bypass route guards?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

My solution was as follows:

My logout method after successfully logging out, redirects the app to the /login route:

@Injectable
export class AuthService {
  // ...
  logout () {
    // do logout
    this.router.navigate(['/login']);
  }
}

My guard is then as follows:

@Injectable
export class DiscardChangesGuard implements CanDeactivate<MyComponent> {

  canDeactivate(component: MyComponent, currentRoute: ActivatedRouteSnapshot,
                currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean> | boolean {

    if (nextState.url === '/login') {
      return true; // bypass checks if we are trying to go to /login
    }

    // perform regular checks here
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

Here's how you can force a bypass on a per-navigation basis. In my case I was navigating back to the account dashboard after the user submits a form with account info.

Ideally you would check for unsaved changes in the form and bypass based on that, but my forms don't have that feature yet.

form component:

this.router.navigateByUrl('/', { state: { bypassFormGuard: true } })

router guard:

@Injectable()
export class ExitFormGuard implements CanDeactivate<ComponentCanDeactivate> {

   constructor(private router: Router) {}

   canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
      if (this.router.getCurrentNavigation()?.extras?.state?.bypassFormGuard) {
         return true
      }

      // perform normal checks
   }
}

about 4 years ago · Santiago Trujillo Relatório

0

My goal was to bypass route guards without touching every route guard in the app, but I was unable to do that. Ultimately I created a new RouteBypassService to inject into every route guard. RouteBypassService implements shouldBypass, which returns true if the route guard should allow navigation for some overriding out of band reason, such as authorization. In my case shouldBypass returns true iff there is no user signed in. (After they sign out, we let them get off the screen no matter what).

It's not ideal because every author of a route guard has to affirmatively remember to add the bypass, but it's not terribly entangling.

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