2017-05-03 123 views
2

當我的用戶在屏幕上有髒變化時,我有一個路由守衛,當他們嘗試離開時提示他們保存或放棄。Angular4路由:通過繞過路由衛士強制導航

但是,如果我由於不活動而將它們註銷,我想要強制導航並繞過護衛(通過放棄其更改),以確保其屏幕處於空白狀態。

我該如何繞過路線衛兵?

回答

1

我的目標是繞過路線衛兵而不觸及應用程序中的每個路線警衛,但我無法做到這一點。最終,我創建了一個新的RouteBypassService以注入每個路線衛兵。 RouteBypassService執行shouldBypass,如果路由警衛應允許導航某些重要的帶外原因(如授權),則返回true。在我的情況下,如果沒有用戶登錄,shouldBypass返回true。(退出後,無論如何,我們都讓他們離開屏幕)。

這並不理想,因爲每一位路線警衛的作者都必須肯定地記得加上旁路,但這並不是非常糾結。

1

我的解決辦法如下:

logout方法成功後退出,應用重定向到/login路線:

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

我的後衛是那麼如下:

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