0

I would like to map a model with nested JSON, but it is not recognizing 'message' id.

I've searched a lot and can not find what's wrong.

Would also like to create an auto-map data comparing JSON with the model (without need to set each value), is that possible?


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:

ERROR TypeError: Cannot set property 'id' of undefined
at PostModel.webpackJsonp.343.PostModel.convert (post.model.ts:10)
...
1
  • First initiate this.message with something, then you can set its fields. Commented Nov 24, 2017 at 19:20

1 Answer 1

2
this.message = {
id: data.message.id,
text: data.message.text
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.