Angular4 Routing: Force Navigation By Bypassing Route Guard

angular, angular4-router

Solution

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

Problem

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?

Original source