i am developing an angular 4 application. once the user wants to log in to the system it sends a http request to the server and server validate the user and it sends a reposnce with a authentication key and other user details. i use local storage to save these information
login() {
if (this.loginForm.valid) {
this.serviceUserService.authenticate(this.loginForm).subscribe(response => {
if (response.message != _err) {
//saving the current user in localstorage
localStorage.setItem('currentUser', JSON.stringify(response.body));
this.router.navigateByUrl('/');
} else {
alert(invalid login. Please try again)
}
}, err => {
console.log(err);
})
}
}
it seems like that localStorage.setItem()
is an asynchronous function. so before it save the curent user in the local storage it redirect to the main page. but since the token is not saved in the local storage no http requests will work. how do i wait until localStorage.setItem()
finish it's task and then send the user to home page.