【问题标题】:Mapping a JSON response to component model in TypeScript.将 JSON 响应映射到 TypeScript 中的组件模型。
【发布时间】:2016-06-01 19:05:16
【问题描述】:

我有一个返回 JSON 字符串的 Angular 2 应用程序。我想获取该 JSON 字符串并将其值映射到模型。

据我了解,TypeScript 模型文件应该有助于将 HTTP Get 响应映射到一个对象——在我的例子中是一个名为“CustomObject”的类。 这是我为 TypeScript 识别而创建的 TypeScript 模型文件:

export class CustomObject {
    public Name: string;
}

这是我的 JSON 字符串的样子(从 Chrome 开发工具稍微修改以消除不必要的变量):

"{
   "EventType": 3,
   "Description": "Test Description",
   "LocationName": "DefaultLocation",
   "Name": "TestName"
}"

我想获取该 JSON 字符串并将“名称”值(“TestName”映射到我在 home.ts 文件中声明的现有 CustomObject 变量,默认情况下为空:

public activeCustomObject: CustomObject = null;

但是,在执行 HTTP Get 方法以检索 JSON 响应之后(我希望变量 'activeCustomObject' 现在将其 'Name' 字段设置为 'TestName',在我的 HTML 文件中调用 {{activeCustomObject.Name}} 不打印任何内容. 我已经完成了正确的导入并设置了提供程序。

这是我订阅的方式:

this._customObjectService.getCustomObject()
    .subscribe(res => {
        this.activeCustomObject = res;
    });

这就是我调用 GET 方法的方式:

getActiveCustomObject() {
    return this._http.get('/test/customobject')
        .map((response) => {
            console.log(response);
            return response.json;
        });
}

关于为什么调用 {{activeCustomObject.Name}} 在我的 HTML 中不打印任何内容的任何想法? Chrome 开发工具显示 JSON 正在返回一个正确的 JSON 字符串,其中包含我需要的数据(主要是名称)。我计划使用 JSON 字符串中的其他值,所以我不能只让 HTTP GET 返回名称字段 - 我需要知道为什么返回的 JSON 字符串没有映射到自定义对象变量。

【问题讨论】:

  • 您的问题解决了吗?
  • 查看 Thierry Templier 接受的答案。

标签: javascript angularjs json typescript angular


【解决方案1】:

我认为这是因为您的数据是异步加载的。我猜你的 JavaScript 控制台有错误...

您可以尝试这样使用 Elvis 运算符:

{{activeCustomObject?.Name}}

我还看到另一个问题。您需要在响应而不是属性上调用json 方法:

getActiveCustomObject() {
  return this._http.get('/test/customobject')
    .map((response) => {
        console.log(response);
        return response.json(); // <-----------
    });
}

【讨论】:

  • 甚至没有看到比 json 方法错字 - 修复了它 - 谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-02-06
  • 2021-12-04
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2016-10-17
相关资源
最近更新 更多