請求

2017-01-09 63 views
1

我有簡單化Angular2應用程序,如果用戶點擊請求

<a class="dropdown-item" (click)=authService.logout() href="/welcome">Log out</a> 

退出菜單項,其中,該AuthenticationServices的logout()方法執行

logout() { 
    alert('loging out'); 
    this.authHttp.post(this.endpoint_url + '/auth/logout','').map(res => { 
    if(res.status == 204) alert('logout successful'); 
    else alert('logout failed'); 
    }); 

    this.currentUser = null; 
    localStorage.removeItem('token'); 
} 

問題是部分

this.authHttp.post(this.endpoint_url + '/auth/logout','').map(res => { 
    if(res.status == 204) alert('logout successful'); 
    else alert('logout failed'); 
    }); 

似乎沒有執行過。使用authHttp(angular2-jwt)訪問受保護的API可在其他應用程序中正常工作,而不會出現任何問題。
第一個警告「註銷」彈出,用戶註銷並重定向到「/ welcome」,並且不能再訪問API的私有部分。但是,瀏覽器和服務器日誌中沒有「/ auth/logout」的請求。


還有AuthGuard服務重定向任何未記錄用戶:

canActivate() { 
//loggedIn() {!(this.currentUser == null);} 
if (!this.auth.loggedIn()) { 
    this.router.navigate(['/welcome']); 
    return false; 
} 
return true; 
} 

回答

1

您需要subscribe的可觀,以「火」起來。

this.authHttp.post(this.endpoint_url + '/auth/logout','').subscribe((res)=>{ 
    if(res.status == 204){ 
    alert('logout successful'); 
    this.currentUser = null; 
    localStorage.removeItem('token'); 
    }else {alert('logout failed');}   
}); 

如果你需要刪除令牌後註銷是全成你需要做這個功能的回調(subscribe)內。

+0

是的,它幫助(部分),以及其他答案(取消點擊事件)。現在它執行,但在令牌被刪除後(因此失敗)。 – wondra

+0

哦,你想要令牌後被刪除?檢查我更新的答案。你可以在res.status == 204裏面或者你喜歡的任何地方刪除令牌 – echonax

+0

發現另一個問題出現在服務器端,再加上錯誤配置的jwt(由於其他組件出現了另一個錯誤)。所有原來的問題都沒有使用'subscribe'。另外,我應該*不*取消該事件。 – wondra