AngularJS service using $http.get is failing to transfer data to a controller

Just getting started with AngularJS and I'm running into some challenges with the basics.

I've been working on a service that uses $http.get to load a couple of Json files. However, when I try to use the service in my controller, I end up with empty arrays.

This is what my service looks like:

app.service('productService', ['$http', function($http){
    var dataList = this;
    dataList.products = [];
    dataList.menu = [];

    $http.get('/prodotti_1.json').success(function(data){
        dataList.products = data;
    });

    $http.get('/menu_1.json').success(function(data){
        dataList.menu = data;
    });
}]);

And here's my controller:

app.controller('ProductController', ['productService', function(productService){
    console.log(productService.products);
    console.log(productService.menu);
}]);

When I check the console, all I see is an empty Array [ ]. If I add console.log(data) inside the success promise, it displays the array correctly. I was under the impression that using "this" instead of $scope would suffice, but it seems like there's something missing in passing the data from the success promise to the controller. I've researched various forums and questions, but haven't found a similar scenario.

For reference, I'm working with Angular 1.4.1. Any insights or guidance would be greatly appreciated.

Thank you

Answer №1

Make sure you wait for the promises to be resolved before accessing the variables. One approach is to return an object with your promises as properties.

app.service('productService', ['$http', function($http){
    return {
         request1: $http.get('/prodotti_1.json'),
         request2: $http.get('/menu_1.json')
       }
}]);

You can then manage these promises in your controller.

app.controller('ProductController', ['productService', function(productService){
    productService.request1.success(function(data){
        //access the data
    });

    productService.request2.success(function(data){
        //access the data
    });
}]);

I hope this solution is helpful.

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

Do not allow navigation to another page until the form has been submitted

As part of my project, I have implemented a feature where new users are required to change their password upon logging into their account for the first time. For new users, the Change Password screen is displayed immediately after login. The menu options ...

The Observable constructor in Nativescript must be called with the 'new' keyword in order to be invoked

I am facing a challenge while attempting to upload a multipart form in nativescript using http-background. The error message "Class constructor Observable cannot be invoked without 'new'" keeps appearing. I have tried changing the compilerOptions ...

Creating a json object using data from an HTML table

I am dealing with HTML returned from a web service that I cannot control. The HTML structure returned by the web service looks like this: <table id="result"> <tbody> <tr> <td><b>Name</b></td> < ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

What is the process for importing Buffer into a Quasar app that is using Vite as the build tool

I'm having issues with integrating the eth-crypto module into my Quasar app that utilizes Vite. The errors I'm encountering are related to the absence of the Buffer object, which is expected since it's typically found in the front end. Is ...

The use of JQuery repeating fields can cause disruptions to the Bootstrap layout when removing rows

I have been struggling with a form that contains multiple fields that need to be repetitive. My current code is functional, but I'm encountering an issue where clicking on any remove button other than the first one causes the fields in the row to rear ...

Tips for creating clickable hyperlinks within a chat platform

I'm currently working on a chat feature for my website that pulls messages from a JSON file and displays them using Vue.js. The issue I'm facing is that when a user includes a link in their message, it does not automatically become clickable beca ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> ...

Transforming an array of JSON objects into a Knockout observable array containing observable properties

My application utilizes an ajax call to fetch a JSON array. [ {"ID":2,"Name":"Name 1","CreatedOn":"/Date(1432892160000)/"}, {"ID":7,"Name":"Name 2","CreatedOn":"/Date(1432892160000)/"}, {"ID":8,"Name":"Name 3","CreatedOn":"/Date(1432892160000)/"}, {"ID":9 ...

States following form submission in an HTTP request may vary

When attempting to submit a form and receive the results on the same page using AJAX, a JavaScript function is called onsubmit, initiating the AJAX call and including the following code: request=new XMLHttpRequest(); /* set up request here ...

Understanding how to deduce parameter types in TypeScript

How can I infer the parameter type? I am working on creating a state management library that is similar to Redux, but I am having trouble defining types for it. Here is the prototype: interface IModel<S, A> { state: S action: IActions<S, A&g ...

What is the reason for the inability to access a global variable type variable outside of the $.each function when used within the $

While analyzing a code snippet, I came across an issue with a variable causing an error. function call(data) { $.each(data, function(index, value) { var ddlId = 'ddlCat' + data[index].docId; var html = '<tr id="supp_doc_row_&ap ...

Struggling to apply the active class using a combination of jquery, nodejs, express, and bootstrap

I've been working on an express generator Node.js application that uses Bootstrap and Jade. I'm facing issues with setting the active state of the navigation bar. After trying to implement some jQuery, I noticed that when I click on the nav bar, ...

If the JSON file exists, load it and add new data without recreating the file or overwriting existing data

Currently, I am in the process of developing a function called createOrLoadJSON(). This function is responsible for checking whether an existing JSON file exists within the application. If the file does not exist, it should create a new file named "userDat ...

When the child content surpasses the height of the parent, you can scroll within an overflow:visible; div

My sidebar navigation menu includes children and sub-children that are revealed on hover. You can view a simplified version of it in this jsfiddle link: https://jsfiddle.net/s096zfpd/ Although the example provided is basic, my main concern arises when the ...

Conflicting Joomla Modules

I'm currently working on a project at the following link: www.eltotaldesign.com/planeteco Within this project, I have integrated the modules DJ Image Slider and Altra Switcher. Despite attempting to install Easy JQuery and other methods, I have been ...

Is it necessary to dispose of node.js domains? When is the appropriate time to do so?

In my Express application, I utilize domains for each incoming request. To ensure that all subsequent middlewares are executed within a domain, I've implemented a middleware. app.use(function(req, res, next) { var d = domain.create(); d.req ...

The setTimeout function fails to behave as intended when used in conjunction with synchronous ajax

Within my code, I have a function that is being invoked multiple times due to iterating through an array of length n and creating 'Plants' with synchronous ajax calls. These calls involve querying the Google Maps API, so it is crucial to throttle ...

The instance is referring to "close" as a property or method during render, but it is not defined. Ensure that this property is reactive and properly defined

Upon my initial foray into Vue.js, I encountered a perplexing warning: vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "success" is not defined on the instance but referenced during render. Make sure that this property is reactive, e ...