首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular 2:在构造函数中解析JSON

Angular 2:在构造函数中解析JSON
EN

Stack Overflow用户
提问于 2017-02-02 15:53:21
回答 1查看 807关注 0票数 0

我正在从服务器发送以下格式的json响应:

代码语言:javascript
运行
复制
{id: Int, name: String,  childJSON: String}

并愿意将其映射到

代码语言:javascript
运行
复制
export class Student{
    constructor(public id: string,
                public name: string,
                public childJSON: ChildObject) {

    }

export class ChildObject {
       constructor(public class: number,
                    public age: number){}

在执行response.json() as Student;时,我得到了{id:1, name: "sumit", childJSON: "{class: 5, age: 10}",即childJSON具有string类型,而不是ChildObject类型。基本上,字符串没有映射到我的子对象。这是实现它的正确方式吗?或者我需要从服务器发送子对象,而不仅仅是JSON字符串

EN

回答 1

Stack Overflow用户

发布于 2017-02-02 16:06:56

您需要在构造函数中手动地“重新水化”对象,而不能使用“参数属性”快捷方式(在构造函数中使用public自动将构造函数参数转换为类属性的技术)。

下面是我会怎么做:

代码语言:javascript
运行
复制
export class Student{
  constructor(options: {
                id: string;
                name: string;
                childJSON: any;
              }) {
    // Now you have to instantiate the class properties one by one.
    this.id = options.id;
    this.name = options.name;
    this.childJSON = new ChildObject(options.childJSON);
  }
}

然后实例化:

代码语言:javascript
运行
复制
const student = new Student(studentJson);

或者,如果您使用一个可观察对象来获取数据:

代码语言:javascript
运行
复制
this.http.get(...).map(...).subscribe(studentJson =>
  this.student = new Student(studentJson)
}

这种解决方案更加灵活,因为您可以直接传递原始JSON对象进行实例化。在您的示例中,您必须编写如下内容:

代码语言:javascript
运行
复制
// NOT GOOD: You must pass each property individually, in the right order...
const student = new Student(studentJson.id, studentJson.name,...);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41996817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档