WannaBeDev
WannaBeDev

Reputation: 47

logout function refreshes the page but it's still logged in

I am following a course on Udemy, the instructor's side is using Angular 2 and I am trying to build the app using the latest version. The main problem I have, is that the logout function is accessed but because I have to refresh the page to display the login form again, for some reason, after the refresh, I see the login form but then it goes back to the part where I'm logged in.

Logout method on the back-end side:

@RequestMapping(value="/loggedOut", method=RequestMethod.POST)
public ResponseEntity logout(){
    SecurityContextHolder.clearContext();
    return new ResponseEntity("Logout Successfully!", HttpStatus.OK);
}

Logout function from my login service:

logOut() {
const url = 'http://localhost:8181/loggedOut';
const basicHeader = 'Basic ' + localStorage.getItem('credentials');
const headers = new HttpHeaders({
  'x-auth-token' : JSON.stringify(localStorage.getItem('xAuthToken')),
  'Authorization' : basicHeader
});
return this.http.post(url, '', { headers, responseType: 'text'});

The button responsible for logging out:

logout() {
  this.loginService.logOut().subscribe(
    res => {
      location.reload();
      console.log("Logged out")
    },
    error => {
      console.log(error)
    }
  );

Technically, it goes as follow: Logged in -> Login form -> Logged in

Logged in: Logged in picture

Log in form: Logged out

If I remove the reload method, I can see that the logout method is accessed and I get a 200 from the back-end.

Logged Out

Network tab before refreshing:

Network tab response

The server response before refreshing:

Server Response

Upvotes: 0

Views: 2697

Answers (2)

Anurag
Anurag

Reputation: 1

**Try This Approach **

logout() {
   this.loginService.logOut().subscribe(
    res => {

      if(res) {
        // clear localStorage
        localStorage.clear();
        //navigate to login component
        this.router.navigate(['loginPagePathName']);
        console.log("Logged out")
      }     
    },
    error => console.log(error));
}

We don't need to refresh the page Note :- You can also clear the local storage whenever login component load into the browser simply put localStorage.clear() inside ngOnInit method of loginComponent

Upvotes: 0

Renis1235
Renis1235

Reputation: 4710

Try clearing out your localStorage when logging out:

localStorage.clear();

Basically, this removes any trace that the app left when logging in.

Upvotes: 2

Related Questions