Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
177
rated 0 times [  184] [ 7]  / answers: 1 / hits: 19674  / 6 Years ago, fri, january 26, 2018, 12:00:00

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.


More From » angular

 Answers
4

In case anyone is getting the same kind of a issue... the reason for this was I have created a variable in my service class to save the current user and set the value for that variable inside the constructor. So, in the login page when the authenticate method gets called it tries to initialize the variable but since user is not logged in yet it is still null. That was causing the issue.


[#55351] Wednesday, January 24, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
helenat

Total Points: 450
Total Questions: 95
Total Answers: 97

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
helenat questions
;