我使用http.get
调用从后端服务器获取JSON对象,并试图从该对象检索数据,但是我收到“ TypeError:obj.attr未定义”。 (注意:我已经验证了JSON对象的发送/接收没有任何问题,并且格式符合预期)。我应该如何引用对象中的特定字段以避免上面的错误?
后端对象数据模型(来自Express users_controller.js
)
exports.user_create_get = function(req, res, next) {
var authObj = new Auth({
dateEffective: {value: moment(Date.now()), attr: {hidden: true}},
username: {value: '', attr: {hidden: false, label: "Username: "}},
password: {value: '', attr: {hidden: false, label: "Password: "}},
mainEmail: {value: '', attr: {hidden: false, label: "Email: "}}
});
var user = new UserObj({
authData: [authObj] })
res.json(user);
};
使用前端Angular代码消耗数据(app.component.ts
):
ngOnInit() {
this.member.getMemberForm().subscribe((data)=>{
this.keys = Object.keys(data["authData"][0]);
this.keys.forEach(key => {
let obj = data["authData"][0][key];
console.log("Key: " + key + "; " +
obj["attr"]["label"]); // <--- ERROR OCCURS HERE
});
if (this.data) this.got_data = true;
});
这是字符串化的JSON对象:
{ "_id": "5ced5e4e7da71157709ef1a6",
"authData": [ { "_id": "5ced5e4e7da71157709ef1a5",
"dateEffective": { "value": 1559060046775,
"attr": { "hidden": true, "label": "Date: " } },
"username": { "value": "",
"attr": { "hidden": false, "label": "Username: " } },
"password": { "value": "",
"attr": { "hidden": false, "label": "Password: " } },
"mainEmail": { "value": "",
"attr": { "hidden": false, "label": "Email: " } } } ]
}