1

I have simplistic Angular2 app, where if user clicks on the

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

logout menu item, the AuthenticationServices's logout() method executes

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'); 
}

the problem is the part

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

does not seem to be ever executed. Accessing protected API with authHttp(angular2-jwt) works in other parts of application without any problems.
The first alert "loging out" pops, users is logged out and redirected to "/welcome" and can no longer access private parts of API. However, there is no request to "/auth/logout" in browser nor in server logs.


There is also AuthGuard service that redirects any non-logged users:

canActivate() {
//loggedIn() {!(this.currentUser == null);}
if (!this.auth.loggedIn()) {
  this.router.navigate(['/welcome']);
  return false;
}
return true;
}
wondra
  • 3,271
  • 3
  • 29
  • 48

1 Answers1

1

You need to subscribe to observables in order to "fire" them.

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');}           
}); 

And if you need to remove the token after the logout is successfull you need to do this inside the functions callback (subscribe).

eko
  • 39,722
  • 10
  • 72
  • 98
  • Yes, it helped(partially), along with other answer (canceling the click event). Now it executes, but after the token was removed(and thus failing). – wondra Jan 09 '17 at 16:51
  • Oh you want token to be removed afterwards? Check my updated answer. You can remove the token inside the res.status == 204 or wherever you like inside the subscribe – eko Jan 09 '17 at 16:52
  • Turns out the other problem was on server side, coupled with mis-configured jwt (which appeared to be working because of another error in other component). All to the original problem was not using `subscribe`. Also, I should *not* cancel the event. – wondra Jan 09 '17 at 17:53
  • @wondra ah, glad you figured it out. – eko Jan 09 '17 at 18:03