Angular 从sessionStorage.getItem()获取空值
我创建了一个服务,在该服务中,我调用API获取用户详细信息并将收到的信息添加到会话存储中,但在调用sessionStorage.getItem'username'时,响应为nullAngular 从sessionStorage.getItem()获取空值,angular,Angular,我创建了一个服务,在该服务中,我调用API获取用户详细信息并将收到的信息添加到会话存储中,但在调用sessionStorage.getItem'username'时,响应为null getUserDetail(email: string, password: string) { this.httpClient.get<User[]>('http://localhost/user/user_login?email=' + email + '&password='
getUserDetail(email: string, password: string) {
this.httpClient.get<User[]>('http://localhost/user/user_login?email=' + email + '&password=' + password).pipe(map(
(user) => {
return user;
}
)).subscribe(
(user: User[]) => {
if (user['isUser'] == true) {
sessionStorage.setItem('username', user['username']);
sessionStorage.setItem('userid', user['userid']);
sessionStorage.setItem('password', password);
sessionStorage.setItem('email', email);
this.router.navigate(['/homepage']);
} else {
console.log(user['error']);
sessionStorage.setItem('login_error', user['error']);
}
}
);
console.log('User From Login: ' + sessionStorage.getItem('username'));
}
当我在我的服务中调用这个api时
this.httpClient.get<List[]>(this.baseURL + 'data_list/get_all_list', { headers: environment.credentialHeaders })
我得到以下错误
TypeError:无法读取null的属性“length”
此错误适用于标题。您正在通过调用httpClient.get从服务器异步请求数据,但您试图通过在调用返回之前检查会话存储来同步获取值: console.log'User From Login:'+sessionStorage.getItem'username' 您应该在subscribe方法中移到行的上方。因为您在设置项之前先获取项。您的代码基本上是这样做的:
// send and asynchronous request here
this.httpClient.get<User[]>(/* args */)
.subscribe(/* stuff to be done AFTER request comes back,
including storing username in session storage */);
// and here we are outside the subscription, the line below gets executed in the same
// event loop tick that the request is sent, long before it comes back.
console.log('User From Login: ' + sessionStorage.getItem('username'));
我使用环境来设置会话值,但它不起作用,我认为环境只加载一次,任何新值都不会在环境中初始化
现在,我在共享服务中设置了我的值,并在任何地方获取这些值,现在它工作正常。当您将数据放入会话存储,然后打开浏览器的开发人员工具并在应用程序选项卡chrome中检查会话存储时,您是否在那里看到了数据?映射操作的意义是什么,顺便说一句?@arnnuem是的,我可以在那里看到会话数据。是的,没关系,你说得对。但当我在环境中访问相同的会话值时,也会出现NULL。是的,这很好,你说得对。但当我在环境中访问相同的会话值时,也会出现NULL。这取决于您查看环境的时刻,在任何情况下,您都应该异步读取该值
// send and asynchronous request here
this.httpClient.get<User[]>(/* args */)
.subscribe(/* stuff to be done AFTER request comes back,
including storing username in session storage */);
// and here we are outside the subscription, the line below gets executed in the same
// event loop tick that the request is sent, long before it comes back.
console.log('User From Login: ' + sessionStorage.getItem('username'));