I have a designed an Angular2 Navbar Component that features a logout button:
import { Component, OnInit } from '@angular/core';
import { LoginService } from '../login.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
loggedIn: boolean;
constructor(private loginService: LoginService, private router : Router) {
if(localStorage.getItem('PortalAdminHasLoggedIn') == '') {
this.loggedIn = false;
} else {
this.loggedIn = true;
}
}
logout(){
this.loginService.logout().subscribe(
res => {
localStorage.setItem('PortalAdminHasLoggedIn', '');
},
err => console.log(err)
);
this.router.navigate(['/login']);
location.reload();
}
getDisplay() {
if(!this.loggedIn){
return "none";
} else {
return "";
}
}
ngOnInit() {
}
}
When the logout button is clicked, what I anticipate is for the logout() function in the LoginService to be executed first, then update the localStorage variable, navigate to the login component, and finally reload the page.
However, there are instances where the page reloads before the logout() function in the LoginService is executed, which results in the localStorage not being updated. How can I modify the code to ensure it executes in the correct order?
Any suggestions or advice would be greatly appreciated. Thank you!