pav*_*rox 5 javascript asynchronous local-storage angular
我正在开发一个角度4应用程序.一旦用户想要登录系统,它就会向服务器发送http请求,服务器验证用户,并发送带有身份验证密钥和其他用户详细信息的reposnce.我使用本地存储来保存这些信息
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);
})
}
}
Run Code Online (Sandbox Code Playgroud)
看起来这localStorage.setItem()
是一个异步函数.因此,在将当前存储中的当前用户保存之前,它会重定向到主页面.但由于令牌未保存在本地存储中,因此http请求不起作用.我如何等待localStorage.setItem()
完成它的任务,然后将用户发送到主页.
你错了,所有 localStorage 调用都是同步的。也许您可以在导航到下一页之前添加检查。
localStorage.setItem('currentUser', JSON.stringify(response.body));
this.router.navigateByUrl('/');
Run Code Online (Sandbox Code Playgroud)
pav*_*rox -3
万一有人遇到同样的问题...原因是我在服务类中创建了一个变量来保存当前用户并在构造函数中设置该变量的值。因此,在登录页面中,当authenticate
调用该方法时,它会尝试初始化变量,但由于用户尚未登录,因此它仍然是null
。这就是导致问题的原因。
归档时间: |
|
查看次数: |
4967 次 |
最近记录: |