簡體   English   中英

Angular2 路由器可以在注銷后激活

[英]Angular2 router canActivate after logout

我對某些路由使用了登錄保護(例如'/profile')。 看起來像這樣:

canActivate() {
    if (this.user.islogin) return true;
    this.router.navigate(['']);
}

如果用戶未登錄並嘗試訪問某些路由,它會將用戶重定向到主頁。 它工作正常。 用戶可以從任何頁面注銷。 我希望我的應用程序具有下一個行為:如果用戶在“/profile”頁面上並單擊“注銷”,他應該通過 canActivate() 方法重定向到主頁。 但是在這種情況下不會調用此方法。 我應該怎么做才能運行 canActivate()(重新加載頁面,手動調用)? 我的注銷方法:

logout() {
    localStorage.removeItem('auth_token');
    this.islogin = false;
}

我試圖添加this.router.navigate([this.router.url]); 注銷方法,但結果是一樣的。 只有當我重新加載頁面時,angular2 才會重定向我。 什么是正確的方法?

考慮到您的守衛只使用islogin並且您在用戶注銷時將其設置為 false,最簡單的方法是在注銷時簡單地重定向:

logout() {
    localStorage.removeItem('auth_token');
    this.islogin = false;
    this.router.navigate(['']);    <---- ADD THIS
}

如果你想在不改變路由的情況下重用canActivate()的邏輯,你可以這樣做:

首先,在您的logout()所在的任何地方注入服務:

constructor(
    private router: Router,
    private route: ActivatedRoute,
    private canActivateGuard: CanActivateGuard) {}

(只需使用您使用的名稱而不是CanActivateGuard

接下來,在logout()調用它:

logout() {
    this.canActivateGuard.canActivate(
        this.route.snapshot,
        this.router.routerState.snapshot);
}

這個問題很老,但問題是當前的。

從 Angular v6 開始,您可以設置路由器的onSameUrlNavigation屬性:

RouterModule.forRoot(routes, {
    ...
    onSameUrlNavigation: 'reload'
})

並在您需要的地方設置runGuardsAndResolvers

{
    path: '',
    component: AccountComponent,
    canActivate: [AuthGuard],
    runGuardsAndResolvers: 'always'
}

在您的注銷方法中,只需調用相同的路由,您的 auth 守衛的canActivate方法就會被觸發:

signout(): void {
    this.store.dispatch({
        type: AuthActionTypes.Signout
    });
    // Navigate to the same url to invoke canActivate method
    // in routes with runGuardsAndResolvers.
    // Also activated onSameUrlNavigation router property.
    this.router.navigate([this.auth.redirectUrl]);
}

在上面的示例中, redirectUrl是保存當前 url 的屬性。

雖然是一個老問題,但我遇到了類似的問題,我只是通過使用async 和 await解決了它

我正在使用AngularFireAuthAngular進行Firebase 身份驗證

當我使用以下代碼時:

  logout(){
    this.fbAuthService.fbSignOut();
    this.router.navigate(['/login']);
  }

用戶已正確注銷,但this.router.navigate(['/login'])不起作用! 如果我重新加載頁面,它會起作用。

后來我懷疑我可能要等待注銷過程完成,然后調用this.router.navigate(['/login']) ) 函數。

所以我把它改成:

  async logout(){
    await this.fbAuthService.fbSignOut();
    this.router.navigate(['/login']);
  }

它就像一個魅力! 希望它可以幫助可能偶然發現此問題的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM