将嵌套的JSON映射到Angular 2中的Model

时间:2017-11-24 18:51:42

标签: json angular

我想使用嵌套的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)
...

1 个答案:

答案 0 :(得分:2)

this.message = {
id: data.message.id,
text: data.message.text
};