【问题标题】:Parse the JSON array object from the Service in the Component从 Component 中的 Service 解析 JSON 数组对象
【发布时间】:2017-11-25 00:18:02
【问题描述】:

这是我从服务传递到组件的响应,我应该在其中向 UI 显示每个值。我需要解析每个值并存储到一个变量中。

[{"profileId":"000234","profileName":"kofi prfl","regionName":"NA  ","fileType":"GRRCN","fileVersion":"1.01","fileFreq":"D01","fileFormat":"FIX","emptyFile":"N","cardMask":"Y","uprInd":"N","dataLevel":"01"}]

this.profileDetailsService.getProfileDetails(this.idDisplay)
      .subscribe(profileResponse => {
          // Should parse the profileResponse here....
          this.searchResult = profileResponse;
          this.spinnerService.hide();
        },
      error => {
          this.spinnerService.hide();
          this.showError();
        }
      );

profileId、profileName、regionName等值如何分隔?

【问题讨论】:

  • 您可以发布更多代码吗?我可以看看你们的服务、模板和组件吗?

标签: json angular object typescript


【解决方案1】:

根据评论代码更新:

您无法访问searchResult 的属性的原因是服务返回的是响应而不是带有属性的Javascript 对象。

来自 HTTP Angular 文档here

响应数据为 JSON 字符串形式。该应用程序必须解析 通过调用 response.json() 将字符串转换为 JavaScript 对象。

我建议在服务中解析响应以保留与 http 请求相关的内容并防止代码重复。

变化:

return this.http.post(this._url, body, options).map((response: Response) => {
    return response;
}).catch((error) => {
    return Observable.throw(error);
});

对此(如果您确实只想要数组中的第一个配置文件):

 return this.http.post(this._url, body, options).map((response: Response) => {
        return response.json()[0];
    }).catch((error) => {
        return Observable.throw(error);
    });

新代码解析 JSON 对象并从数组中提取第一个对象.json()[0]。然后将profileResponse 重命名为profileDetails 并使用点符号访问this.searchResult 的属性:

例如从组件中的另一个函数: console.log(this.searchResult.profileName)

例如从您的模板: {{searchResult.profileName}}

【讨论】:

  • profileResponse.profileId 不显示字段中的值。它只是在控制台中显示未定义。
  • 您确定返回的是实际对象而不是服务中的 json 字符串吗?您的服务是否调用 response.json()?
  • return this.http.post(this._url, body, options) .map((response:Response) => { return response; }) .catch((error) => { return Observable .throw(错误); }); this.profileDetailsS​​ervice.getProfileDetails(this.idDisplay) .subscribe(profileResponse => { this.value1 = profileResponse.profileId; this.value2 = profileResponse.profileName; this.searchResult = profileResponse; console.log("stringify values is "+ JSON .stringify(this.searchResult)); this.spinnerService.hide(); } );
  • 这就是我将响应从服务传递到组件的方式。
【解决方案2】:

而不是在您的代码中:

...
this.searchResult = profileResponse;
...

你可以使用:

searchResult: any[];

...
this.searchResult = profileResponse.json() || {}
...

然后您可以通过 searchResult 项访问每个​​属性:

this.searchResult[0].profileId, etc

【讨论】:

  • 这就像一个魅力!为此挣扎了将近8个小时。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多