【问题标题】:Angular 4 / Typescript JSON FormattingAngular 4 / Typescript JSON 格式
【发布时间】:2018-03-28 01:51:59
【问题描述】:

我正在开发一个 Angular 4 应用程序,它通过获取和发送 JSON 请求来与 REST API 对话。

当我准备要发布的 JSON 请求时,我做了大量的手动工作来构建 JSON..

我确信使用库或打字稿技巧一定有比下面更好的方法。但一直找不到,我正在寻找建议。

const addressJson = ' { \n ' + this.jsonFormatField('Address', serviceAddress.address) + ',' +
            this.jsonFormatField('Address2', serviceAddress.address2) + '\n,' +
            this.jsonFormatField('City', address3) + '\n,' +

【问题讨论】:

    标签: json angular rest typescript


    【解决方案1】:

    Angular 会为你将一个对象序列化为 JSON:

    const address = {
        Address: serviceAddress.address,
        Address2: serviceAddress.address2,
        City: address3
    };
    
    http
      .post('/your/rest/endpoint', address)
      // subscribe() is still necessary when using post().
      .subscribe(...);
    

    【讨论】:

      【解决方案2】:

      你试过JSON.stringify吗?它接受一个常规的 JavaScript 对象作为输入,并为它生成一个包含相关 JSON 的字符串。

      【讨论】:

      • 我想我的问题是在我的应用程序中我有一个 JSON 对象 X 与 JSON 对象 Y 我发布的 API 需要的属性略有不同...我想我可以在Y的结构然后填写X的属性会更干净吗?
      • 绝对应该这样做。通常对于 API 的请求和响应数据,您需要 dto,这是为相关 API 量身定制的轻量级对象。应用程序使用的类型不必完全映射到此,事实上,它们可能会从您使用的各种框架中添加很多包袱。因此,在客户端应用程序中使用的类型和 API 可以理解的类型之间进行某种显式转换是一个好主意。在添加和删除字段时,这是值得的。
      猜你喜欢
      • 1970-01-01
      • 2018-12-06
      • 2020-08-05
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2018-11-14
      • 1970-01-01
      相关资源
      最近更新 更多