How to wait for localStorage.setItem to end in angular 4

I am developing an angular 4. application, as soon as the user wants to log in, he sends an HTTP request to the server, and the server checks the user and sends a reposition with the authentication key and other user data. I use local storage to store this 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 to be localStorage.setItem()an asynchronous function. therefore, before saving the current user to local storage, he is redirected to the main page. but since the token is not stored in local storage, no HTTP requests will work. how can I wait until the localStorage.setItem()task is completed and then send the user to the home page.

+4
2

, - ​​ . , . , , . .

0

, localStorage . , .

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

Source: https://habr.com/ru/post/1692751/


All Articles