简体   繁体   English

如何在Angular 8中访问JSON响应中的数据?

[英]How to access data in JSON response in Angular 8?

I am getting data back from a web-server and I am trying to access the data within the JSON object. I am having some issues with accessing it.我正在从网络服务器取回数据,我正在尝试访问 JSON object 中的数据。我在访问它时遇到了一些问题。

The JSON looks like this: JSON 看起来像这样:

{
     "faults": [
      {
        "FaultCodeType": "X",
        "ErrorType": "System",
        "Description": "Response failed for reason 1"
      },
      {
        "FaultCodeType": "Y",
        "ErrorType": "System",
        "Description": "Response failed for reason 2"
      }
     ],
     "responseInfo": {},
     "responseInfo2": {},
     "responseInfo3": {}
}

Should I use JSON.parse?我应该使用 JSON.parse 吗?

JSON.stringify? JSON.stringify?

I have the method:我有方法:

loadData(dataPassed) {
  this.angularService.searchWithData(dataPassed).subscribe(
data => {
const fault = data[0];
const fault2 = data[1];
console.log('Data is here = ' + data); // returns the JSON
console.log('Request = ' + JSON.stringify(data)); // shows the JSON
console.log(fault);  // undefined
console.log(fault2); // undefined
  }
}

It is not working though, any help would be greatly appreciated.虽然它不起作用,但我们将不胜感激任何帮助。

You are getting undefined because of你变得不确定是因为

const fault = data[0];
const fault2 = data[1];

as your data is object not array therefore fault[0] does not exists因为你的数据是 object 不是数组因此故障 [0] 不存在

try尝试

const fault = data.faults[0];
const fault2 = data.faults[1];

To access faults :访问faults

const faults = data.faults;

Then you can iterate over those faults :然后你可以迭代这些faults

faults.forEach(f -> {
     console.log('f.FaultCodeType', f.FaultCodeType);
     console.log('f.ErrorType', f.ErrorType);
     console.log('f.Description', f.Description);
})

To access responseInfo , responseInfo2 or responseInfo3 :要访问responseInforesponseInfo2responseInfo3

console.log('data.responseInfo', data.responseInfo);
console.log('data.responseInfo2', data.responseInfo2);
console.log('data.responseInfo3', data.responseInfo3);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM