AngularJS中如何访问JSON的isEmployeeOJ字段?当前获取返回undefined
如何正确访问JSON中的
isEmployeeOJ字段? 嘿,我一眼就瞅出问题所在啦!
先理清楚你的场景:
你请求到的JSON数据是这样的:
{"discountPriceValues":[[{"Price":"3.0"},{"Scode":"S0375102"}],[{"Price":"2.0"},{"Scode":"s0779548"}]],"isEmployeeOJ":"Y"}
你的AngularJS代码写法是:
var test = $http.get("data/test.json").then(function (response5) { $scope.testing = response5.data; return response5; }); test.then(function(testing){ $scope.testing = testing.data.discountPriceValues; //console.log($scope.testing); });
当你尝试console.log($scope.testing.isEmployeeOJ)时得到undefined,核心原因是:你在第二个then里把$scope.testing给覆盖了!
第一次then里,你把整个JSON根对象赋值给了$scope.testing,这时候$scope.testing.isEmployeeOJ其实是能正常拿到"Y"的。但紧接着第二个then,你把$scope.testing改成了testing.data.discountPriceValues——也就是JSON里的那个二维数组,数组本身没有isEmployeeOJ这个属性,所以访问它自然返回undefined。
给你两种解决思路,按需选择:
思路1:保留完整根数据,单独存储折扣价格数组
如果需要同时操作isEmployeeOJ和discountPriceValues,可以把它们分别存在不同的作用域变量里,一次then就能搞定:
$http.get("data/test.json").then(function (response) { // 存储完整的根数据,这样能访问所有字段 $scope.testData = response.data; // 单独把折扣价格数组存起来,方便后续业务使用 $scope.discountPrices = response.data.discountPriceValues; // 现在就能正常访问啦 console.log($scope.testData.isEmployeeOJ); // 输出 "Y" });
这样你既可以用$scope.discountPrices处理价格列表,也能通过$scope.testData.isEmployeeOJ拿到员工标识的值,逻辑更清晰。
思路2:直接提取需要的字段
如果不需要完整的根数据,也可以直接把isEmployeeOJ单独存到作用域:
$http.get("data/test.json").then(function (response) { $scope.discountPrices = response.data.discountPriceValues; $scope.isEmployee = response.data.isEmployeeOJ; console.log($scope.isEmployee); // 输出 "Y" });
另外提一句,你原来的代码用了两次then链式调用其实没必要,一次then就能完成所有数据赋值,这样代码更简洁也不容易出现变量覆盖的问题哦~
内容的提问来源于stack exchange,提问作者user3774781
相关产品推荐
相关产品推荐

