Retrieving an array of JSON data from an HTTP response

Recently starting my journey with AngularJS for a project, I've encountered a challenge in extracting a json array from an http response to utilize in a list.

Here's a glimpse of the response structure:

{
  "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 snippet for the resource and request implementation is as follows:

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

In addition, the pertinent controller code appears 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);

However, I'm currently facing an issue at the mentioned line. How can I successfully extract the desired array? A 'TypeError' is thrown when attempting to access 'ca_inquire_request':

TypeError: Cannot read property 'ca_inquire_request' of undefined

Answer №1

Revise

 $scope.debug = getCatalog.query();

Replace it with

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

In this updated code, the API call has been converted into a promise. Previously, your code was logging the variable before the response had arrived.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: Shadcn-UI Form Alert - An element is converting an uncontrolled input to controlled mode

Throughout the course of this project, I found myself repeatedly using const [fileNames, setFileNames] = useState<string[]>([]); and logging the state with console.log(fileNames). However, every time I clicked on the parent element, an empty Array e ...

Is it possible to monitor the progress of an order placed via my website as a Flipkart affiliate?

As an affiliate for flipkart, I promote their products on my website. I am interested in being able to track the orders and purchases made by users who are redirected to flipkart from my site. Is it possible for us to obtain the order/purchase id for thos ...

Issues with data binding in Angular2 are arising specifically in IE11

After successfully loading the application on Chrome, Firefox, and Edge, I encountered difficulties when trying to load it on IE11. The data bindings were not created properly, despite the internal data being fetched correctly through a websocket connectio ...

Is there a way to turn off step navigation in bootstrap?

Displayed below is a visual representation of the bootstrap step navigation component. Presently, there is an unseen 'next' button located at the bottom of the page. When this 'next' button is pressed, it transitions from 'step-1 ...

Automated Recommendation Selector

I'm searching for a JavaScript library that can provide the following functionalities: An auto-suggest dropdown list that uses Ajax to retrieve results from a database. Restricting the user to only select values provided by the Ajax call. Abilit ...

Tips for customizing the appearance of the tooltip in echart using Angular

Need help with echart tooltip formatting. If you'd like to take a look at the code, click here: https://stackblitz.com/edit/angular-ngx-echarts-ty4mlq?file=src/app/app.component.ts const xAxisData = []; const data1 = []; const data2 = []; const data ...

AngularJS single-page application with model-view-controller style designs

Hey there, I'm relatively new to AngularJS and currently on a steep learning curve. I've been working on developing an AngularJS SPA and have grasped the basics. I'm using ngRoute for routing and have put together a basic application framew ...

Alert message in jQuery validation for the chosen option value

I am attempting to validate a combo box with the code provided below. Currently, I receive multiple alert messages even if one condition is true. My goal is to only display one alert message when a condition is met and highlight the other values in red. Th ...

Enhancing a component with injected props by including type definitions in a higher-order component

Implementing a "higher order component" without types can be achieved as shown below: const Themeable = (mapThemeToProps) => { return (WrappedComponent) => { const themedComponent = (props, { theme: appTheme }) => { return <Wrapped ...

What is the most effective method for storing a three.js scene on a server?

Currently, I am in the process of developing a web application that utilizes three.js for rendering 3D models. One of the features I have already implemented is the ability to create a project by selecting a base model (which can be in various formats such ...

Nested asynchronous mapping in Node.js involving multiple HTTP requests

Currently, I am attempting to iterate through an array of URLs and retrieve responses from a specific set of URLs. The goal is for the outer loop to only proceed after all inner requests have been completed, resulting in the desired outcome as shown below: ...

Caution: The function is returning a 'float (*)[3]' datatype, which is incompatible with the expected return type 'float *'

I keep encountering the error 'warning: returning ‘float (*)[3]’ from a function with incompatible return type ‘float *' when I attempt to return an array within a function. While I understand that C has limitations when it comes to returni ...

Updating the Ajax Url dynamically while scrolling

I am trying to update the Ajax URL dynamically, and here is my progress so far: var size=1; var from = 1; window.addEventListener('mousewheel', function(e){ if(e.wheelDelta<0 && from<5){ from++; } else if(e.whe ...

Partial functionality achieved by integrating Bootstrap for a modal form in Rails

Having an issue with a form in a partial view on Rails 3.2.3 utilizing the bootstrap 2.0.2 modals #myModal.modal .modal-header .close{"data-dismiss" => "modal"}= link_to "x", root_path %h3 Add Tags .modal-body = form_tag '/tagging& ...

CarouFredSel Transition Troubles

I am currently using CarouFredSel to create an image carousel, but I am encountering some issues with the transitions between items. My goal is to incorporate simple HTML elements into the carousel instead of just plain images. However, when I attempt to ...

Using Angular: connecting $viewContentLoaded to manually initiate app bootstrapping

I have an Angular module that I am bootstrapping manually and attempting to access its $rootScope to add an event listener for $viewContentLoaded. Below is the code snippet: angular.bootstrap(el, [appname]); //////////////////////////// Fixing links cons ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Learn how to extract precise information from a JSON array by utilizing Angular 6

After making a GET request in Angular 6, I successfully retrieved data from a JSON array. Now, I have this JSON data as an example and my goal is to find the team(s) that employee "TEST4KRWN" is part of. Can anyone guide me on how to write a JSON query us ...

Extracting data from a webpage's dynamic table using Python with Selenium and

I am planning to extract the data from the JavaScript tables found in the following link: import codecs import lxml.html as lh from lxml import etree import requests from selenium import webdriver import urllib2 from bs4 import BeautifulSoup URL = &apo ...

Navigating arrays containing arrays/objects and updating properties in Angular using loops

My challenge involves an array containing arrays and objects. Within a function, I am attempting to assign a value to a specific property (for example, setting 'call' of $scope.companies[0].users to the value selected in a checkbox). Despite my r ...