我是一个项目的AngularJS新手,我正试图从一个http响应中提取一个json数组,以便在列表中使用。
响应如下:
{
"DFH0XCMNOperationResponse": {
"ca_return_code": 0,
"ca_inquire_request": {
"ca_last_item_ref": 150,
"ca_item_count": 15,
"ca_cat_item": [
{
"ca_cost": "002.90",
"in_stock": 119,
"ca_description": "Ball Pens Black 24pk",
"on_order": 0,
"ca_department": 10,
"ca_item_ref": 10
},
{
"ca_cost": "002.90",
"in_stock": 6,
"ca_description": "Ball Pens Blue 24pk",
"on_order": 50,
"ca_department": 10,
"ca_item_ref": 20
}
],
"ca_list_start_ref": 0
},
"ca_response_message": "+15 ITEMS RETURNED",
"ca_request_id": "01INQC"
}
}
资源和请求的代码如下所示:
.factory('getCatalog', ['$resource', function($resource){
return $resource('catalogmanagertest/v1/apps/bca45894-92f7-49dc-ae54-b23b89ab6c73/catalog', {}, {query: {method:'POST'}});
}]);
相关的控制器代码如下所示:
angular
.module('catalogController', ['ngMaterial', 'ngResource'])
.controller('catalogController', ['$scope', 'getCatalog', 'catalog', function($scope, getCatalog, catalog) {
$scope.debug = getCatalog.query(); // set scope catalog to array from zOS
$scope.catalog = catalog.ca_cat_item;
$scope.message = "This is a test order message";
this.tiles = buildGridModel({
icon : "avatar:svg-",
title: "",
cost: "€",
background: "",
stock: ""
});
function buildGridModel(tileTmpl){
var it, results = [ ];
var tmp = $scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item;
console.log(tmp);
倒数第二行是我遇到的麻烦。如何提取预期的数组?我在执行console.log时遇到新手错误:
TypeError: Cannot read property 'ca_inquire_request' of undefined
答案 0 :(得分:4)
替换
$scope.debug = getCatalog.query();
带
getCatalog.query().$promise.then(function (result) {
$scope.debug = result;
console.log($scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item);
});
在这里您可以看到我刚刚将api调用转换为promise。在您的代码中,控制台在响应来之前记录变量。