Retrieving JSON data in array by making an AngularJS resource call

Developed a factory that returns JSON data and calling it from the controller, but the data is returning empty. I'm not sure where I went wrong. There are no console errors and in the network tab, the JSON data is also loading.


'use strict';
var app = angular.module('angularJson', ['ngResource']);

app.factory('loadJsonService', ['$resource', function ($resource) {
    return {
        getData: function () {
            return $resource('json/productDetails.json');
        }
    };
}])

app.controller('angularJsonCtrl',['$scope', 'loadJsonService',function($scope, loadJsonService){

$scope.loadProducts = function(noOfData){
    $scope.productDetails = [];
    $scope.productDetails = loadJsonService.getData().query();
}

}]);

Answer №1

Ensure you wait for the request to complete before using .$promise.then after calling the $resource.query function. This way, you can define a function that will be called upon the success of the API call.

loadJsonService.getData().query().$promise.then(function(res){ //success function
   $scope.productDetails = res;
}, function(error){ //error function
   console.log(error);
})

Answer №2

To successfully use the getData function, make sure to structure your $http request in the following way:

$http.jsonp("json/productDetails.json")
        .then(function(response) {
          handleResponse(response);
        });

Answer №3

Experiment with the built-in query method. If you prefer crafting your own custom get method, follow these steps:

{
   method: 'GET',
   params: {
      key: value
   },
   isArray: true,
   cache: true // enable caching if desired
}

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

Transferring data from a dropdown menu to a different PHP file using AJAX

Modification functions are designated for the chosen item in the combobox. The textbox serves as the input. Once the final value is entered into the textbox, the JavaScript variables are effectively transmitted, but an empty alert is displayed. <script ...

Challenges with Media Queries post Integration of MUI Library in React

I have been scratching my head for the last few hours. I needed to utilize a react library to design my dog app for a project. Opting for the MUI library, it has been effective for the grid layout. However, the challenge arises when attempting to implement ...

Is there a way to determine the desired width of an element using jQuery prior to rendering it?

I am currently facing an issue with an element that has not yet been added to the body. Despite having all the necessary classes for a specific box model, I am unable to determine its width before it is appended. When inspecting the element using Firebug, ...

Is there a way to give a ReactJS button a pressed appearance when a key is pressed?

I recently developed a Drum Machine using ReactJS, but I'm facing an issue with making the buttons look like they've been clicked when I press the corresponding key. I came across a similar query on this site, however, I'm having trouble imp ...

How can I create reactivity for this hook in Vue 3?

So here's the deal, I have this hook code snippet that goes like this: export const useOpeningHours = ( flight: Ref<FlightOption | null>, identifier: string, isEnabled?: boolean ) => { if (!flight.value) { return { show: fa ...

How can you identify when an input value has been modified in Angular?

For my current project, I am developing a directive to be used with a text input field in order to format currency input. This directive has two HostListeners - one for when the input loses focus and one for when it gains focus. When the blur event occurs, ...

Guide to linking a specific event with JQuery event handlers

I have a Javascript function named Howto that is triggered by a button press: function howto(){ $('#elementtoupdate').ajaxSend(function() { //Code to run }); $('#elementtoupdate').ajaxComplete(function() { //Co ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

Creating a loading screen in Angular2: Step-by-step guide

How can you best integrate a preloader in Angular 2? ...

I am having trouble retrieving child interface data from API using Angular. Can someone help me figure out what I am doing

Recently started with Angular 7 and could use some guidance. I have a JSON stream that appears as follows: { "Id": 25, "Name": "XYZ Corp", "CompanyAddresses": [ { "Id": 39, "CompanyId": 25, "Address1 ...

AngluarJS and LeafletJS Integration Issue with Geojson Object

During my project, I attempted to synchronize filters with geojson data displayed in a table and on a map. Initially, I utilized Angular and the angular-leaflet-directive, but the performance was too slow for my requirements. Subsequently, I made the decis ...

Utilize the value of one input-number field as the maximum value for another field

I am looking for a solution to save the value of an input-number field in order to set it as the maximum value for another input-number field. What is the most effective method to achieve this task? Whether it be through PHP, JavaScript, jQuery or any othe ...

Implementing PHP code to fetch a JSON array and store it in a database

I have an invitation table and I am sending the data in JSON format using Postman. I need to send multiple invitations at once, so I want to insert multiple invitations. Is there a way to achieve this? Currently, I have only created a single invitation. ...

Building an interactive grid using AngularJS

As a newcomer to angularjs, I am aiming to create a grid of 12*12. I managed to achieve this using the following methods - 1. Employ nested for loops and add elements to the parent div accordingly. 2. Develop a static grid. Unfortunately, neither of thes ...

jQuery: automatic submission on pressing enter compared to the browser's autocomplete feature

Here is a JavaScript code snippet that automatically submits the form when the user presses the "enter" key: jQuery.fn.installDefaultButton = function() { $('form input, form select').live('keypress', function(e) { if ((e.which && ...

ReactJS and MaterialUI: Creating a Dynamic Triangle Button Slider

I am facing a challenge in creating a triangle-shaped button for a slider in Material UI and ReactJS, instead of the current pizza slice shape. Here is an example of the desired outcome: https://i.sstatic.net/pNn93.png Here is the current state of the sl ...

v-treeview component triggering method execution twice upon input

I'm facing an issue with my Vue component that contains a treeview. Upon selecting a node, the goal is to update an array and display the checkbox as selected. However, I'm encountering a problem where if I select elements from one folder in the ...

Arranging xCharts based on the weekday order

Struggling with xCharts, specifically trying to display a bar chart showing numbers with corresponding days of the week in order. Despite my efforts, I can't seem to get them to appear in the correct sequence. Refer to the image below for reference: ...

Which Angular tools should I be using: map, pipe, or tap?

When my component initializes, I retrieve data from the server import {Rules} from "../../interfaces/interfaces"; rules: Rules ngOnInit() { this.tt = this.rulesService.getUserClientRules().subscribe( t => { console.log(t) con ...

Illustrate an element positioned beneath a child element within a different element

I am in the process of designing an overlay on a Google Map that resembles a real map placed on a table, using 2 pixel lines as creases above the map. This design does not significantly impact interactions with the map; only 6 out of 500 vertical lines are ...