简体   繁体   中英

how to wait until localStorage.setItem finishes in angular 4

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.

You are wrong , all localStorage calls are synchronous . Probably you can add a check before navigating to the next page.

 localStorage.setItem('currentUser', JSON.stringify(response.body));     
 this.router.navigateByUrl('/');

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM