我想使用嵌套的JSON映射模型,但它无法识别'message'id
。
我经常搜索,找不到什么错误。
还想创建一个自动地图数据,将JSON与模型进行比较(无需设置每个值),这可能吗?
JSON DATA:
{
"author": "John Doe",
"message": {
"id": 32133,
"text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
}
}
post.model.ts
export class PostModel {
author: string;
message: PostMessageModel;
constructor() { }
convert(data: any) {
this.author = data.author;
this.message.id = data.message.id; // ERROR HERE
this.message.text = data.message.text;
...
}
}
interface PostMessageModel {
id: number;
text: string;
}
错误:
ERROR TypeError: Cannot set property 'id' of undefined
at PostModel.webpackJsonp.343.PostModel.convert (post.model.ts:10)
...
答案 0 :(得分:2)
this.message = {
id: data.message.id,
text: data.message.text
};