Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems.

The console log appears as follows 👇

https://i.sstatic.net/GDXkC.png

It does not work with ngResource. Check out the CodePen link for an example: http://codepen.io/anon/pen/dMbRXx

On the other hand, it works perfectly fine when using a variable. Here's the working example: http://codepen.io/anon/pen/ONLgNX

var app = angular.module('app', ['ngResource']);
app.controller('myCtrl', function($scope, categoryFilter) {
  $scope.resultItems = categoryFilter.query();
  $scope.resultIndex = $scope.resultItems[0];
  $scope.resultIndexItem = $scope.resultItems[0].status;
});
app.factory('categoryFilter', function($resource) {
  return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, {
    query: {
      method: "GET"
    }
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.5.0/angular-resource.min.js"></script>

<div class="container" ng-app="app" ng-controller="myCtrl">
  <div class="col-xs-12">
    <h3>ngResource result</h3>
    <pre>{{resultItems | json }}</pre>
    <hr />
    <pre>{{resultIndex | json }}</pre>
    <hr />
    <pre>{{resultIndexItem | json}}</pre>
  </div>
</div>

Answer â„–1

Every individual asset functions as an ajax request, meaning it operates asynchronously. Thus, utilizing callbacks within the query function is essential. Your code should resemble this:

var app = angular.module('app', ['ngResource']);
app.controller('myCtrl', function($scope, categoryFilter) {
  categoryFilter.query(function(results){
    $scope.resultItems  = results;
    $scope.resultIndexItem = $scope.resultItems.status;
  });    
});
app.factory('categoryFilter', function($resource) {
  return $resource("https://maps.googleapis.com/maps/api/geocode/json?address=NY", {}, {
    query: {
      method: "GET"
    }
  });
});

link

Update

If I have misunderstood your question, please accept my apologies. All elements enclosed in {} in json format are considered objects and can be accessed using a period (.). For example, in json, results and status are objects, while items inside square brackets ([]) represent arrays that can be accessed using an index.

From json https://i.sstatic.net/5sPFd.gif https://i.sstatic.net/kFiwB.gif

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

Retrieve the HTML tag content as a string using jQuery

For my OSINT project, I am developing a tool that needs to extract text from a specific HTML code string. $("p").text(); I'm looking for a way to make my variable work with the above code. Any suggestions? Share your ideas! Solution: $.ajax({ ...

Enhancing functionality with extra JavaScript tags in next.js

Recently, I delved into programming with react & next.js after previously working with node.js. It didn't take long for me to create my first application, but upon inspecting the page, I noticed an abundance of extra JavaScript code (see image below). ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

NextJs redirection techniquesWould you like to learn the best ways

Currently, I am developing an application using NextJS with Firebase authentication integration. Upon successful authentication, my goal is to retrieve additional customer details stored in a MongoDB database or create a new document for the customer upon ...

Transform a Postgres array into an object

I have been attempting to construct an object from my table, and I currently have a query that produces the following output: How can I transform this result into the format below: answerId | json 1|{"en":["Autoimmune","Bronchitis ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

Parsing data from the JSON Shell command

I have a JSON array that looks like this. [ { "release": "2008.1006", "kernel": "2.6.32-754.3.5", "os": "6.10", "current": true }, { "release": "2008.1006", "kernel": "3.10.0-862.14.4", "os": "7.5", "current": true } ] When I use ${#array[@]} to print th ...

When using the onclick function, an unexpected behavior occurs where instead of displaying content, the page

Below is a summarized version of my code: HTML <a onclick="showHideDiv('bio')" target='_self'> bio <div id="bio" class="shadowScreen" style="display: none;"> <p class="showBio"> Bio! </p> &l ...

Conceal and Reveal every marker on the map

Creating a map using angular to display data on the web page and Google Map is my current project. This is my first major project utilizing Angular, and I have nearly achieved the functionality as planned. I am eager to enhance the site with more user-fri ...

Utilize jQuery to extract various input/select box values and compile them into an array for submission using .ajax()

I am currently facing an issue with dynamically generated forms using PHP and updated with jQuery's .appendTo() function as visitors interact with it. My main goal is to collect all input text and select box values from the current form and submit the ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

To successfully display the data on my ChartJS Line graph, I have to first click on the color legend

I am currently using Chart JS to visualize sensor data retrieved from a firebase firestore database. I've come across an unusual issue where my chart fails to display the data initially >> https://i.sstatic.net/qD6Sd.jpg but after performing two ...

Convert a JavaScript object into a serialized form

Alright, so here's the thing that's been bugging me. I have this JavaScript object that I need to pass to a PHP script using jQuery AJAX. But every time I try to pass it as is, I get an error. It seems like the object needs to be serialized befor ...

The contents of a JSON Object will not be logged by Node, no matter the approach

I am currently encoding data for a Node.js WebSocket server in JSON format. When attempting to display the contents of the JSON object on the server side, I am encountering the issue where Node simply logs object Object I have experimented with the follow ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

What is the best way to query based on a nested object property in Mongoose?

const collection = [ { inner_obj: { prop: "A" } } ] Get the outer records by searching for the ones that match the value of the `prop` property within the `inner_obj` column. How can we locate the o ...

Modify the div's visibility based on selected option in the dropdown menu

In my PHP file, I have the following codes: <section id="placeOrder"> <h2>Place order</h2> Your details Customer Type: <select name="customerType"> <option value="">Customer Type?</option> <option value="ret ...

Instead of printing only the JSON data using "response.data", the entire response is being printed out

I'm making a GET request from an AngularJS 1.5x client to a Java HTTP method. In the client, I want to display the response that includes some JSON data. // This is a method from an Angular service that sends AJAX requests this.getTask = function(tas ...

What is the best way to trigger a snackbar notification when two passwords do not match?

I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...

Using Python to convert JSON documents into PostgreSQL records

Struggling to convert a JSON document into PostgreSQL records using Python, especially when dealing with nested structures. Need help in combining two strings - header and value strings. Feeling overwhelmed by the complexity of nested vocabularies in a JSO ...