Receiving an error when trying to access the 'get' property of $http within a nested function

Encountering the following error

angular.js:13550 TypeError: Cannot read property 'get' of undefined at Object.DataService.getDataFromAPI

I seem to be struggling with the $HTTP.get function. Any insights on what might be going wrong or how to resolve it? I suspect the issue lies in passing the $HTTP into the nested function.

(function (module) { 'use strict';

DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {


var getDataFromAPI = function ($http) {


        $http.get("http://localhost:34183/myAPI")
        .then(function (response) {
            console.log(response);
            console.log(response.data);
            return response.data;
        });

    };
}
 return {
            getDataFromAPI: getDataFromAPI
};
}

    module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

Showcasing that the method works when directly embedding the JSON data.

 DataService.$inject = ['$http', '$q'];
 function DataService($http, $q) {

 var getDataFromAPI = function ($http) {
        return [{
                  "Grade": "A+",
                  "Class": {
                      "Subject": "Select Topics in Basket Weaving",
                      "Professor": "DJ Khaled"
                  }            
               }];
    };
return {
            getDataFromAPI: getDataFromAPI
};
}
module.factory('DataService', DataService);

})(angular.module('ClassAPP'));

Answer №1

Make sure to include an object return statement within the factory function

function DataFetcher($http, $q) {


    var fetchDataFromServer = function () {        

      return $http.get("http://example.com/myData")
            .then(function (response) {
                console.log(response);
                console.log(response.data);
                return response.data;
            });

        };

      return {
           fetchDataFromServer : fetchDataFromServer
       }
    }

Answer №2

Could you please format it this way?

app.service("ApiService", ["$http", function($http){
    return {
        fetchDataFromServer: function(endpoint) {
            return $http.get(endpoint);
        }
    };
}]);

How to Use:

fetchDataFromServer.fetchDataFromServer('/api/endpoint/');

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

Adding text to an existing div element using jQuery and ensuring the div tag automatically adjusts its height according to the text length

I have attempted to implement the following code, but unfortunately, it is not functioning as expected. I am hopeful that someone can assist me. I am seeking a way for the div tag to dynamically increase its height based on the size of the text. Does any ...

Comparison between bo-html and bo-text

As I was going through the documentation for the bindonce directive, a question popped into my head regarding the distinction between bo-html and bo-text. bo-html: This evaluates "markup" and displays it as HTML within the element. bo-text: ...

Ever tried asynchronous iteration with promises?

I have a specific code snippet that I am working on, which involves registering multiple socketio namespaces. Certain aspects of the functionality rely on database calls using sequelize, hence requiring the use of promises. In this scenario, I intend for t ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

Enhance Website User Experience: Keeping Track of Scroll Position When Users Navigate Back in Browser

Have you ever experienced the frustration of scrolling through a page with infinite scroll, only to click on a link and then go back to find that you've lost your place in the scroll? You're scrolling down a lot, You click on a link from the i ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

Using JavaScript to browse and filter by category

After spending some time working on a search function, I received some assistance from Tim Down who provided me with a simple code to search for specific text within a page. Now, my goal is to modify the code to enable searching by category. I have struct ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Tips for integrating AngularJS into a webpage

I am currently developing a NodeJS application and I am looking to integrate AngularJS for the client side scripting. After downloading AngularJS via NPM, I encountered an issue where my require statement is not functioning as expected. Can anyone provide ...

Spring Boot fails to recognize path variable data sent from Angular

When working with Angular 7, I encountered a situation where I needed to pass a value from the service class of Angular. Here is how I achieved it: executeHelloWorldBeanServiceWithPathVariable(name){ console.log("name coming from here"+name); retu ...

ReactJS encountered an error: [function] is not defined, July 2017

Attempting to convert a JSON file into an array and then randomly selecting 5 items from it. I suspect the issue lies in my render/return statement at the end of ImageContainer.js, but as a newbie in ReactJS, it could be anything. Any assistance or guida ...

Utilizing a Function Across Controllers in AngularJS: A Guide

When developing my angularjs application, I decided to create two separate modules - 'home' and 'templates'. I am now faced with the challenge of utilizing functions from one module in the other. Here's how I approached it: Modu ...

Node.js: Leveraging Express to Compare URL Parameters and Handle Delete Requests with Array Values

Having some issues with the Express routes I set up for an array of objects and CRUD operations. Everything works smoothly except for the "Delete" operation. I am trying to delete an object by matching its URL parameter ID with the value of its key. Howev ...

Vue.js: The chart's dataset has been refreshed

I am utilizing vue-chart.js to create a basic chart. import { Line } from 'vue-chartjs'; export default { extends: Line, mounted() { this.renderChart({ labels: [this.getChartLabels], datasets: [ { label: &a ...

Create a link for editing in a data table that can filter based on multiple column values and also enable global search on specific custom

How can I generate an edit link with a function that requires multiple parameters extracted from different data columns received via ajax? I have come across the render callback, but it seems to only return one column value at a time and my requirement is ...

Encountering issues when trying to incorporate SASS and CSS libraries in NextJS

I have been attempting to integrate the wix-style-react plugin into my NextJS project, but I am encountering difficulties when trying to build. According to their documentation, they utilize Stylable, SASS, and CSS Modules. After installing the plugin and ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

A solution for managing MUI data grid rows and columns using useRef to prevent infinite loops when handling onSortModelChange

I am encountering a similar issue as described in the question below. A suggestion was given to utilize useRef to encapsulate rows and columns and access its .current value. How can I implement this solution?? Material-UI Data Grid onSortModelChange Causi ...

Obtain the session value in React

Currently, I am working on a React app along with a server-side application. I have successfully created a user session on the server side and now I want to retrieve its value in my React app. Can someone guide me on how to achieve this? const [user,setUse ...