无法访问JSON获取错误

时间:2018-06-19 14:04:43

标签: json angular

我无法访问json。 PFB json

我正在尝试访问:-

this.businessSwitchName = d.businessSwitchDetails.nodeName;

并尝试通过插值绑定到html

var d:any = {
    "service": "091PUNE623017759708",
    "routerDetails": {
        "nodeName": null,
        "portName": null,
        "nodeIP": null,
        "nodeID": null
    },
    "agsDetails": {
        "nodeName": null,
        "portName": null,
        "nodeIP": null,
        "nodeID": null
    },
    "businessSwitchDetails": {
        "nodeName": "Dyaneshwar Park",
        "portName": null,
        "nodeIP": "10.171.4.3",
        "nodeID": "365429"
    },
    "handoffPort": null,
    "qosLoopingPort": null
}

但是出现此错误:

this error

ERROR TypeError: Cannot read property 'businessSwitchDetails' of undefined
    at ContactFormComponent.push../src/app/contact-form/contact-form.component.ts.ContactFormComponent.onChange (contact-form.component.ts:16)
    at Object.eval (ContactFormComponent.html:48)
    at handleEvent (core.js:9953)
    at callWithDebugContext (core.js:11046)
    at Object.debugHandleEvent [as handleEvent] (core.js:10749)
    at dispatchEvent (core.js:7415)
    at core.js:7859
    at HTMLInputElement.<anonymous> (platform-browser.js:1140)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:3662)

2 个答案:

答案 0 :(得分:0)

我无法评论,因此需要在答案中进行此操作,但是您需要显示更多信息。

在哪里初始化变量d,因为似乎d与businessSwitchName不在同一范围内


您尝试使用变量d后对其进行初始化。 这意味着您尝试执行以下操作:

this.businessSwitchName = d.businessSwitchDetails.nodeName;

变量d仍未定义,因此您应该先定义d,然后再对其进行处理。

因此,使您的onChange()方法如下:

onChange(){
var d = {"service": "091PUNE623017759708",
"routerDetails": {
    "nodeName": null,
    "portName": null,
    "nodeIP": null,
    "nodeID": null
},
"agsDetails": {
    "nodeName": null,
    "portName": null,
    "nodeIP": null,
    "nodeID": null
},
"businessSwitchDetails": {
    "nodeName": "Dyaneshwar Park",
    "portName": null,
    "nodeIP": "10.171.4.3",
    "nodeID": "365429"
},
"handoffPort": null,
"qosLoopingPort": null};


  this.businessSwitchName = d.businessSwitchDetails.nodeName;
  this.businessSwitchIp = d.businessSwitchDetails.nodeIP;
  this.portName = d.businessSwitchDetails.portName;

  let da = {
  "serviceAttribute": {
    "serviceType": "GVPN",
    "category": "category",
    "name": "091PUNE623017759708"
  },
  "btsIp": "10.171.4.3"
};

  console.log(da);

  this.service.portService(da).
    subscribe (response => {
        console.log(response);

    });  
}

}

答案 1 :(得分:0)

  

TypeError:无法读取未定义的属性'businessSwitchDetails'

正如上面的声明所言,我们要访问businessSwitchDetails的{​​{1}}属性,并声明未定义对象undefined

调试方式:

  • 在此行代码d之前执行console.log(d);,以检查您是否获得了正确的响应。

  • 检查this.businessSwitchName = d.businessSwitchDetails.nodeName;的值。应该是d而不是JSON object

  • 检查语句的执行顺序。首先应该是对象JSON string的初始化,然后是语句以访问属性d