【发布时间】:2018-04-23 06:52:37
【问题描述】:
我正在尝试将 JSON 解析为类对象,但它总是返回错误。
JSON 字符串 - 这是我在 allResourceString 中得到的
[
{
"resourceName":"12 strong",
"resourceType":"Movie",
"summary":"12 Strong tells the story of the first Special Forces team deployed to Afghanistan after 9/11; under the leadership of a new captain, the team must work with an Afghan warlord to take down for the Taliban.",
"director":"Nicolai Fuglsig",
"length":130,
"yearDate":2018,
"uploadDate":"2018-04-20T21:00:00.000Z",
"totalGrade":0,
"img":"XkFtZTgwNjY2NDczNDM@._V1_SY1000_CR0,0,674,1000_AL_.jpg",
"genre":"Action,Drama,History"
},
...
]
类:
export class Resource {
public resourceName: string;
public resourceType: string;
public summary: string;
public director: string;
public length: number;
public yearDate: number;
public uploadDate: Date;
public totalGrade: number;
public img: string;
public genre: string;
}
解析 JSON:
allResource: Array<Resource>;
i: number;
constructor(private httpService: HttpService) { }
ngOnInit() {
this.httpService.httpGet('')
.subscribe(
(response) => {
this.allResourceString = response.text();
this.allResource = <Array<Resource>>JSON.parse(this.allResourceString);
},
(error) => console.log(error),
);
for (this.i = 0; this.i < this.allResource.length; this.i++) {
...
}
}
它总是返回
错误类型错误:无法读取未定义的属性“长度” 在 HomeComponent.ngOnInit (home.component.ts:35)
【问题讨论】:
-
this.allResource = >JSON.parse(...语法无效。 -
这是因为
this.allResource是在订阅中设置的。这意味着它是异步执行的。您的for循环在该订阅之外,这意味着它在设置this.allResource之前执行。另外,您可以使用 response.json() 代替 response.text(),它会自动为您解析,因此无需调用 JSON.parse
标签: javascript angular