简体   繁体   English

如何等到localStorage.setItem以角度4结束

[英]how to wait until localStorage.setItem finishes in angular 4

i am developing an angular 4 application. 我正在开发一个角度4应用程序。 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. 一旦用户想要登录系统,它就会向服务器发送http请求,服务器验证用户,并发送带有身份验证密钥和其他用户详细信息的reposnce。 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. 似乎localStorage.setItem()是一个异步函数。 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. 但由于令牌未保存在本地存储中,因此http请求不起作用。 how do i wait until localStorage.setItem() finish it's task and then send the user to home page. 我如何等待localStorage.setItem()完成它的任务,然后将用户发送到主页。

You are wrong , all localStorage calls are synchronous . 你错了,所有localStorage调用都是同步的 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 . 因此,在登录页面中,当调用authenticate方法时,它会尝试初始化变量,但由于用户尚未登录,因此它仍然为null That was causing the issue. 这导致了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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