简体   繁体   中英

Extracting json array from http response

I'm new to AngularJS for a project and I'm trying to extract a json array from a http response to use in a list.

The response looks like this:

{
  "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"
  }
}

The code for the resource and request looks like this:

.factory('getCatalog', ['$resource', function($resource){
    return $resource('catalogmanagertest/v1/apps/bca45894-92f7-49dc-ae54-b23b89ab6c73/catalog', {}, {query: {method:'POST'}});
}]);

And the controller code relevant looks like this:

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);

The next to last line is what I'm having trouble with. How do extract the expected array? I get the newbie error when I do the console.log:

TypeError: Cannot read property 'ca_inquire_request' of undefined

Replace

 $scope.debug = getCatalog.query();

with

  getCatalog.query().$promise.then(function (result) {
       $scope.debug = result;
       console.log($scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item);
    });

Here You can see I just converted api call into the promise.In your code before console is logging variable before response come.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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