Search code examples
javascriptangularjsasynchronoushttprequestdeferred

Get back the value of a HTTP Request in Angular JS


I try to create a function which makes a HTTP Request in Javascript and to get the result of this request. Unfortunately, I absolutely don't know how to get back this result in an other function..

Find here both of my function (both should do the same thing) :

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

And the other one :

$scope.getInfo = 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 have found a lot of articles about the way to make the request but not to get back its value (a simple call of the function in an other one just display "object object" and I didn't find a solution to display it correctly).

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

Could you help me please?


Solution

  • You should proceed like this when using Promise :

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

    Your current code return a Promise, that's why the result returned by getInfo is considered as an object

    If you want getInfo to be a function you can do like this :

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