Chen
Chen

Reputation: 23

Angular $http.get not return data

I created a helper service to wrap the $http.get.

self.apiGet = function (url, success, failure, always) {
           
            $http.get(url)
                .then(function (result) {
                    success(result);
                    if (always != null)
                        always();
                }, function (result) {
                    if (failure != null) {
                        failure(result);
                    }
                    else {

                    }
                    if (always != null)
                        always();
                });
        }

In my controller class, the data is not returned to the view when calling getData(val). the data is returned from the api when I debug it.

 $scope.getData = function (val) {
        return helper.apiGet(url,
            function (result) {
                return result.data;
            });
    }; 

Upvotes: 1

Views: 1450

Answers (1)

dfsq
dfsq

Reputation: 193301

You should just use promises properly. So the service becomes:

self.apiGet = function(url) {
    return $http.get(url).then(function(result) {
        return result.data;
    });
};

... and it's consumed in controller like this:

helper.apiGet(url).then(function(data) {
    $scope.data = data;
});

Upvotes: 4

Related Questions