从Component中的Service解析JSON数组对象

时间:2017-06-21 22:23:36

标签: json angular object typescript

这是我从服务传递到组件的响应,我应该在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等,值?

2 个答案:

答案 0 :(得分:2)

代替您的代码:

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

你可以使用:

searchResult: any[];

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

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

this.searchResult[0].profileId, etc

答案 1 :(得分:0)

根据评论代码进行更新:

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

来自HTTP Angular docs 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的属性:

e.g。从组件中的另一个函数: console.log(this.searchResult.profileName)

e.g。从您的模板: {{searchResult.profileName}}