Obtaining a JSON object from a URL through 'GET' request using $resource in AngularJS

Just starting out with AngularJS and struggling to understand web services as well. My current task involves fetching a JSON object from the following URL:

To retrieve the JSON object, I need to access:

I am completely lost on how to proceed... Any assistance in modifying my code would be greatly appreciated.

Thank you in advance! Below is the JavaScript code I have:

'use strict';

var services = angular.module('services', ['ngResource']);

services.factory('dataFactory', ['$resource','$http', '$log',
        function ($resource, $http, $log) {
                return {
                    getAllUsers: function(){
                        return  $resource('http://mylocalhostname.dev/users/list',{city_id:12}
                            ,{
                                locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter)
                                  $log.info(data.UsersList[0]);
                                  return data.UsersList[0].userName;
                                })}
                            }
                        );
                    }
                } 
    }]); 

Upon testing, I receive the following message in my console:

GET 200 OK 164ms angular.js (line 7772) (in red color) (an empty string)

Answer №1

(Although this question is quite old and still without a solution, it popped up at the top of my recent search results. Hopefully, I can help close this particular loop)

Here is a straightforward example of a controller fetching data from a basic factory. The factory uses $resource to access a file hosted locally and then returns the contents of that file back to the controller.

The factory:

'use strict';
angular.module('myApp')
  .factory('myFactory', ['$resource', function($resource) {
     return function(fileName){
       return $resource(fileName, {});
     };
  }]);

The controller:

'use strict';
var fileToGet = 'some/path/to/file.json';
angular.module('myApp')
    .controller('myController', function($scope, myFactory) {
   var getDefs = new myFactory(fileToGet).get(function(data) {
      $scope.wholeFile = data;
      // $scope.wholeFile now holds the complete JSON-formatted object

      $scope.someSection = data.section;
      // $scope.someSection now contains the "varX" and "varY" items

      $scope.myStringX = JSON.stringify(data.section.varX);
      // retrieves the stringified value 
   });
});

The JSON-formatted file:

{
  "someVar": "xyz",
  "someArray": [
    {
      "element0A": "foo",
      "element0B": "bar"
    },
    {
      "element1A": "man",
      "element1B": "chu"
    }
  ],
  "section": {
     "varX": 0,
     "varY": "yyyy"
  }
}

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

The ng-model directive template in Angular JS fails to function properly when used inside the ng-switch directive

In order to enhance the dynamic nature of my directive, a decision was made to incorporate the category field for selecting the type of template to be displayed. Instead of using multiple html files, it was proposed to use ng-switch -ng within this context ...

Dealing with models in Vue.js is proving to be quite a challenge

Why isn't myGame showing as 超級馬力歐 initially and changing when the button is pressed? It just displays {{myGame}} instead. I'm not sure how to fix it, thank you! let myApp = new vue({ el:'myApp', data:{ myGame:&a ...

Having difficulties executing a JavaScript file in the command prompt

I'm having trouble running a JavaScript file in the command prompt. Can anyone assist me with this issue? D:\>Node Welcome to Node.js v12.14.1. Type ".help" for more information. > 001.js undefined > Node 001.js Thrown: Node 001.js ...

Attempting to store data types such as json, jsonb, hstore, xml, enum, ipaddr, etc. results in an error message indicating that the column "x" is of type json whereas the expression is of type character varying

When PostgreSQL is used to store data in a field with a string-like validated type such as xml, json, jsonb, xml, ltree, etc., encountering an error during an INSERT or UPDATE process is common. The error message might look like this: column "the_col" is ...

Fill out the form field using an AJAX request

Whenever a specific business is selected from a dropdown list, I want to automatically populate a Django form field. For example: I have a list of businesses (business A, business B, ...) and corresponding countries where each business is located. Busin ...

Steps to verify the functionality of an uploaded wcf service on a web server

I need help determining if my wcf web service project, which I have recently uploaded to my existing GoDaddy web server, is accessible on the internet. Can anyone provide guidance on how to verify the accessibility of the web service online? ...

A pair of variables combined within a set of single quotation marks

After exploring numerous examples, I am still struggling to include a variable inside quotes. This situation seems unique and difficult to resolve. Take a look at the code snippet below: Var x='http://www.xyzftp/myservice/service1.svc' Var y=&a ...

Pass the selected value from the view to the controller using filters

I am using the ng-repeat function to display an array of objects. One of the attributes in the array is video duration, and I have implemented a filter to directly calculate the sum of all meta_durations. Here is the code for the filter: app.filter(' ...

Keep clicking on the Protractor element until it becomes enabled

I am facing an issue while trying to write a test where my results are displayed on multiple pages. I can navigate to the next page by clicking a button, but if the button is disabled, I need to handle that scenario. How can I achieve this with Protractor? ...

Submitting a nested object to a Spring MVC controller through JSON format

In my controller, I have defined a POST handler like this: @RequestMapping(value="/ajax/saveVendor.do", method = RequestMethod.POST) public @ResponseBody AjaxResponse saveVendor( @Valid UIVendor vendor, Bindin ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...

Obtain marker icons from a text column in a fusion table using the Google Maps API

I am currently working with javascript and the v3 version of the maps API to retrieve data from a Fusion Table. I have been able to add custom markers to specific points successfully, but now I am attempting to set default icons for the markers I create ba ...

"Utilizing jQuery and AJAX to manage identical-named option boxes with

I am encountering an issue with multiple select boxes that share the same name. Currently, when I choose a value from one select box, it submits that selection and updates the database. However, when I select an item from another select box, it still submi ...

Is it recommended to use django's render_to_string response with innerHTML?

This is my first Django project, so please bear with me if I'm making some basic mistakes. I'm currently working on a webpage that will display a report in an HTML table. However, I feel like the process I'm using to gather the data and cons ...

Display the item for which the date is more recent than today's date

Is there a way to display only upcoming 'events' on my page based on their event_date? <% for (let event of events){%> <div class="card mb-3"> <div class="row"> <div class="col ...

The method JSONObject.toString() will provide a snapshot of the data

Currently, I am retrieving JSON data from a web service located here. My goal is to save the exact text of the result object onto the SD card. The issue arises when I invoke the toString() method as it does not provide the entire data as a string. To view ...

What could be the reason for the malfunctioning of my express delete request?

When I send a delete request using Postman on my localhost, everything functions correctly. However, when trying to make the same request from my React.js client-side, it doesn't go through. Below is the API request: router.delete("/deletetransaction ...

What is the best way to assign a value to this.var within a function nested in the same class in JavaScript?

Can anyone help me figure out why I can't set the this.session variable from within the last this.rpc using this.setSession()? I am new to JavaScript classes and transitioning from PHP, so I'm struggling with this concept. function glpirpc(host, ...

Submitting a form in React/Javascript: A step-by-step guide

I have a website on Wordpress where I am using the Wp-Polls plugin to vote. How can I submit a post request by accessing a form URL in a React project? Specifically, how can I vote for the "Bad" option with a value of 2? The HTML structure of the WordPre ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...