Angular 6项目:我无法为localStorage设置密钥,也无法检索本地存储数据
有人可以帮我吗?
UserService.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserService {
authToken;
user;
constructor(private http: HttpClient) { }
addUser(a) {
return this.http.post('/api/register', a);
}
authUser(data) {
return this.http.post('/api/login', data);
}
storeUserData(token, user) {
this.authToken = token;
this.user = user;
let akey = localStorage.key('token');
let bkey = localStorage.key('userData');
localStorage.setItem(akey, this.authToken);
localStorage.setItem(bkey, JSON.stringify(this.user));
//OR
localStorage.setItem('token', token);
localStorage.setItem('userData', user);
}
}
User.component.ts: 触发服务功能的功能
loginUser(data) {
this.userService.authUser(data).subscribe(data => {
console.log(data.user);
if(!data.success) {
this.authErr = true;
console.log('Error Occured!');
} else {
this.authErr = false;
this.router.navigate(['/dashboard']);
this.userService.storeUserData(data.token, data.user);
}
});
}
答案 0 :(得分:1)
您是否具有覆盖本地存储键/值列表的值面板?
这是我的PC上的本地存储列表:
注意,在悬停时可以单击并拖动中间的水平栏。
在您发布的屏幕快照中,看起来下半部分面板已被向上拖动,因此覆盖了上半部分,因此您实际上并没有查看按键。像这样
答案 1 :(得分:0)
我怀疑您的代码永远不会被调用。看这两行:
this.router.navigate(['/dashboard']);
this.userService.storeUserData(data.token, data.user);
似乎您先导航离开,然后尝试存储数据。如果交换线路会怎样?
答案 2 :(得分:0)
只需尝试
localStorage.setItem("userKey", JSON.stringify(this.user));
确保
user
不是null
或undefined
,