Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function.

Here are the two functions I've tried (both intended to achieve the same goal):

$scope.getData = function() {
        return $http({
            method: 'GET',
            url: 'https://api.net'
        }).then(function (response) {
            return response.data;
        });
    };

And the alternative approach:

$scope.getData = function() {
        var defer = $q.defer();
        $http.get('https://api.net').then(function(response) {
            defer.resolve(response.data);
        }, function(response) {
            defer.reject(response);
        });
        return defer.promise;
    };

I've read several articles on making HTTP requests, but I can't seem to figure out how to properly handle and display the retrieved data. Simply calling the function within another one results in displaying "[Object object]" instead of the actual data.

$scope.displayData = function() {
        var myValue = $scope.getData();
        alert(myValue); /* shows [Object object] */
    };

Any assistance would be greatly appreciated!

Answer №1

When working with Promises, it is recommended to follow this pattern:

 $http({
     method: 'GET',
     url: 'https://api.net'
 }).then(function (response) {
     $scope.info = response.data
 });

The current code returns a Promise, which is why the output of getInfo is treated as an object.

If you prefer getInfo to be a function, you can rewrite it like so:

$scope.getInfo = function() {
    return $http({
        method: 'GET',
        url: 'https://api.net'
    }).then(function (response) {
        return response.data;
    });
};

$scope.getInfo().then(function(result) {
   alert(result);
});

Answer №2

One common error when using the $http service is mistakenly assigning the return value of its methods to a variable that is a promise, which is not the intended behavior.

Let's analyze the code snippet below:

$scope.getInfo = function() {
        return $http({
            method: 'GET',
            url: 'https://api.net'
        }).then(function (response) {
            return response.data;
        }).catch(function(error){
            // handle the error
            throw error;
        });
    };

The getInfo function is designed to return a promise that will eventually resolve to the desired data value.

If you were to use it in your controller like this:

$scope.test = function() {
        var myValue = $scope.getInfo();
        alert(myValue); /* displays [Object object] */
    };

You would notice that myValue holds a promise (you can verify by doing a console.log(myValue)). A suggested approach would be utilizing the function as follows:

 $scope.test = function() {
        $scope.getInfo()
           .then(function(response){
                var myValue = response.data;
                alert(myValue); /* shows [Object object] */
           }).catch(function(error) {
                console.error(error);
                throw error;
           })

    };

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

Next.js is causing me some trouble by adding an unnecessary top margin in my index.js file

I started a new project using next.js by running the command: yarn create next-app However, I noticed that all heading and paragraph tags in my code have default top margins in next.js. index.js import React, { Component } from "react"; import ...

Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur. In order to address this issue, I require all default component imports from a .vue file to include the file exten ...

Is there a specific method to access a JSON file with (js/node.js)?

Searching for a way to access user information stored in a JSON file using the fs module in node.js. Specifically looking to read only one user at a time. app.get("/1", function(req, res) { fs.readFile("users.json",function(data, err){res.write(data)}} W ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

Optimizing the rendering of Font-awesome CDN JS for better performance on Pagespeed Insights

Instead of directly linking to the Font Awesome CSS, I have chosen to leverage the JavaScript provided by the trustworthy and efficient Font Awesome CDN. This allows for asynchronous loading of icons on my homepage, ensuring a seamless user experience. How ...

A guide on utilizing the javascript function to toggle the checkbox in each row of a gridview

I am looking to implement a function that checks checkboxes row by row based on specific conditions. The first condition requires an alert popup if three checkboxes are selected in the same row consecutively ("You can't select continuous three hou ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Limiting the functionality of API's to be exclusively accessible within the confines of a web browser

Currently, I am working with node js and have implemented policies to restrict API access from sources other than the browser. In order to achieve this, I have included the following condition in my code: app.route('/students').all(policy.checkH ...

State is causing a conflict by allowing multiple menus to open when mapping over Menu objects

I am currently encountering an issue with my Material UI <Menu>. The problem arises when I attempt to display some data and interface functionality by mapping over a <Card>, along with adding an <IconButton> on each card that opens a menu ...

When a login attempt is unsuccessful, I am redirected to /api/auth/error using next-auth

Currently, I am utilizing next-auth version 4.18.8 on my login page for the final project of my Fullstack JS course. It's worth noting that a more recent version is being used compared to what was taught in the course (next-auth v. 3). Upon entering ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

How can I retrieve the Google Maps URL containing a 'placeid' using AJAX?

I have a specific URL that I can access through my browser to see JSON data. The URL appears as follows: https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE However, when I attempt to use jQuer ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

Making a POST request across domains without relying on any third-party frameworks

Is it possible to create a cross-domain request using vanilla JavaScript without relying on frameworks like jQuery? I am looking to send a JSON to a service on a different domain and receive the response using a callback function. Can this be done solely ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

The PKIJS digital signature does not align with the verification process

Explore the code snippet below const data = await Deno.readFile("./README.md"); const certificate = (await loadPEM("./playground/domain.pem"))[0] as Certificate; const privateKey = (await loadPEM("./playground/domain-pk ...

Choose an element by its specific data attribute

I have come across this html code and I am attempting to assign a new class to it using the data attribute: <p class="form-row form-row-wide" data-child-field="child_has_jacket"> </p> Even after trying with jQuery : jQuery( ...