Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data.

var app = angular.module("ReciboApp",[]);
    // -------- SERVICES ------------------- 
    app.service("ABMService", function($http){
        this.getData = function(url){
            $http.get(url)
                .success(function(data) {
                    var results = eval(data);
                    console.log(results); //[Object, Object, Object, Object, Object]
                    return results;                                                   
                })
                .error(function(data) {
                    console.log('Error: ' + data);
                });
        }
    });
// -------- CONTROLLERS -------------------
// -- Companies --
var companiesController = function($scope, ABMService){
    var url = "models/companies_json.php";
    $scope.companies = [];
    $scope.companies = ABMService.getData(url);
    console.log($scope.companies); //undefined
}
app.controller("CompaniesCtrl", companiesController);

Answer №1

Your function called obtenerDatos does not actually return anything; it simply makes an asynchronous call to $http. To fix this, try returning the result of the $http call, which is an angular promise. Then, in your controller, you can attach a .then handler to the returned promise:

var app = angular.module("ReciboApp", []);
    // -------- SERVICES ------------------- 
    app.service("ABMService", function($http) {
        this.obtenerDatos = function(url) {

            // add a return statement here
            return $http.get(url)

                // change .success() to .then()
                .then(function(data) {
                    datos = eval(data);
                    console.log(datos); //[Object, Object, Object, Object, Object]
                    return datos;                                                    
                })

                // change .error() to .catch()
                .catch(function(data) {
                    console.log('Error: ' + data);
                });
        }
    });
// -------- CONTROLLERS -------------------
// -- Companies --
var companiesController = function($scope, ABMService) {
    var url = "models/companies_json.php";
    $scope.companies = [];

    // wait for the obtenerDatos() call to complete, and then
    // assign the returned data to the $scope
    ABMService.obtenerDatos(url).then(function(datos) {
        $scope.companies = ABMService.obtenerDatos(url);
        console.log($scope.companies); //undefined
    });
}
app.controller("CompaniesCtrl", companiesController);

Also, please take note that I have replaced the .success() and .error() callbacks with .then() and .catch() respectively, as the former methods have been deprecated.

Answer №2

Appreciate your help! I found the solution with the guidance of Nicholas Graziano. Check it out here

app.factory('MYAPI', function($http) {
    return {
        obtainData: function(url) {
            return $http.get(url);
        }
    }
});
var companiesController = function($scope, MYAPI){
    var url= "models/companies_json.php";
    MYAPI.obtainData(url).then(function(response) {
        $scope.companies = eval(response.data);
    }, function(error) {
        console.error(error);
});
app.controller("CompaniesCtrl", companiesController);

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

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

Tips for determining if a user is refreshing the page or navigating to a different page

Scenario: I need to store a specific variable in the local storage every time a user exits the page. By utilizing the window.onbeforeunload method, I am able to capture the event when a user is leaving the page. However, I want to assign different values ...

How to effectively test $transition service hooks in UI-Router 1.X using karma?

I have been working on migrating to ui-router 1.0.5 and have made good progress, but I am having trouble finding examples of how to test the new transition hooks that replaced the $stateChangeXXX event listeners. Previous Code: scope.$on('$stateChan ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

Changing the value in a URL String using JavaScript

I am in possession of a String that contains a URL resembling the following: var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jg ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

Exploring the integration of data from two Firestore collections using JavaScript

I manage two different types of collections, one being called CURRENCY-PAIR and the other Alerts. The collection CURRENCY-PAIR includes the following information: Currency-Pair Name Currency-AskPrice Currency-BidPrice On the other hand, the Alerts colle ...

Unable to showcase the chosen option utilizing select2

Utilizing angular-ui's select2 directive has been a bit of a challenge. While the functionality is there, I've encountered an issue where the selected value isn't being displayed properly due to my implementation workaround. <select ...

Adding Packages to AngularJS: A Step-by-Step Guide

Recently, I decided to dive into learning AngularJS and NPM on my own. Using the book Professional AngularJS by Diego Netto and Valeri Karpov as my guide, I successfully installed the application with Yeoman and ran it using Grunt. However, I've hit ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...

Adjusting value of one input field according to the content of another text field in an

Just starting out with Angular and I am looking to dynamically change the value of a hidden input field called 'cc_card' based on the first digit entered in another input field called 'cc_number'. For example, if the user enters 5 in &a ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

Loading a different webpage seamlessly without having to reload the current one

Here is a snippet of my code in okay.html: {% extends "sch/base.html" %} {% load staticfiles %} {% block content %} <div class="row" id="ada"> <form action="" method="post> {% csrf_token %} <div align="center" class="cont ...

Creating interactive comments in Vue 3 using dynamic rendering

Is there a way to properly display a dynamic comment in Vue 3? I attempted using v-html, but it's not working as expected in my scenario. Here is the example: <template> <!-- Method 1: not displaying correctly, https://i.sstatic.net/ddX39. ...

JavaScript can extract a portion of an array

Is it possible to generate a new array consisting of all elements ranging from the nth to the (n+k)th positions within an existing array? ...

Determine the specific value of an HTML table cell by specifying the column name for a specific row

One challenge I am facing is dynamically creating a table using JSON without knowing in advance the number of columns and/or rows that will be generated. I have successfully added a clicked event for the row that gets selected. In every table, there will ...

determining the quantity within a collection of items

Is there a way to determine the order of an element within a set when clicked? For example, if I click on the third element in a set, can I get it to display as three? Check out this jsfiddle example for reference: http://jsfiddle.net/vtt3d/ ...

Dealing with Request Disconnection in a Node.js and Express Application

I have a node/express application and I am looking for a way to detect unexpected interruptions in the connection. I have attempted using the following code: req.on('close', function () { //this handles browser/tab closure scenarios }) Howev ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...