我还是使用Typescript的新手,我想从这个localStorage只输出用户名:
localStorage.getItem('currentUser')
目前正在输出: { “的用户名”: “根”, “密码”: “根”}
我该怎么做?
答案 0 :(得分:1)
简短回答:使用JSON.parse
将字符串转换回对象:
var user = JSON.parse(localStorage.getItem('currentUser'));
console.log(user.username);
(注意:这通常适用于JavaScript,而不仅仅是TypeScript)
<强>详情
项目作为字符串存储在localStorage
中。因此,要在localStorage
中保存对象,请使用JSON.stringify(obj)
将其转换为字符串。 (将您的用户对象保存到localStorage
的人可能会使用此方法。)
要转换回对象,请使用JSON.parse(str)
。请注意,如果字符串不是对象的有效JSON表示,则会抛出异常。
使用您的用户对象的所有示例(如果您删除类型声明,它也是有效的JavaScript):
interface IUser {
username: string;
password: string; // please don't do this in real code
}
function saveCurrentUser(user: IUser): void {
localStorage.setItem('currentUser', JSON.stringify(user));
}
function getCurrentUser(): IUser {
var userStr = localStorage.getItem('currentUser');
try {
return JSON.parse(userStr);
} catch (ex) {
return null; // or do some other error handling
}
}
var user = { username: 'root', password: 'root' };
saveCurrentUser(user);
// elsewhere...
var savedUser = getCurrentUser();
if (savedUser) {
console.log('Current user: ' + savedUser.username);
} else {
console.log('Current user not found');
}
答案 1 :(得分:1)
您需要使用 JSON.parse
var user = JSON.parse(localStorage.getItem('currentUser'));
然后访问其中的用户名字段
if(user){
console.log(user.username);
}