[英]How to get data in and out of typescript interface from JSON string in Angular
I am trying to set a user object from a JSON string gotten from localStorage.我正在尝试从从 localStorage 获得的 JSON 字符串设置用户 object。
let jsonObj: any =
JSON.parse(localStorage.getItem('userId'));
this.user = (jsonObj as User)
This call:这个电话:
console.log(JSON.stringify(this.user));
Produces the expected result:产生预期的结果:
[{"firstName":"Thom","lastName":"Thumb","username":"Tiny",
"password":"123456","streetAddress":"587 Elm St.",
"city":"Cleveland","state":"Ohio","country":"USA",
"postalCode":"45678","email":"thom.thumb@gmail.com","id":5}]
However, when I try to extract a specific value:但是,当我尝试提取特定值时:
console.log(this.user.username);
It returns undefined.它返回未定义。 I need to extract the value to assign it to another object.
我需要提取该值以将其分配给另一个 object。
This is what 'user' looks like:这就是“用户”的样子:
export interface User {
id: number;
username: string;
password: string;
firstName: string;
lastName: string;
streetAddress: string;
city: string;
state: string;
country: string;
postalCode: string;
email: string;
token: string;
}
You are getting an array of user.您将获得一组用户。 Use:-
利用:-
console.log(this.user[0].username);
As you can see in your given output, it starts with [ and ends with ],this means it is an array.正如您在给定的 output 中看到的那样,它以 [ 开头并以 ] 结尾,这意味着它是一个数组。
[{"firstName":"Thom","lastName":"Thumb","username":"Tiny", "password":"123456","streetAddress":"587 Elm St.", "city":"Cleveland","state":"Ohio","country":"USA", "postalCode":"45678","email":"thom.thumb@gmail.com","id":5}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.