0

I am trying to write a simple service in AngularJS that calls my API and returns the data.

I need to get the value from $http's response.data into my variable responseData.

angular.module('app.services', [])

.service('API', ['$http', function($http){

    this.call = function(type, params) {
        var url = "{API url here}";
        var key = "{API key here}";
        var responseData;

        url += type + ".php";
        params.key = key;

        $http({
            method: "GET",
            url: url,
            params: params
        })
        .then(function successCallback(response) {
            console.log(response);
            responseData = response.data;

        }, function errorCallback(response) {
            console.log(response);
            responseData = {success:false, error:"Could not connect"};
        });
        return responseData;
    };
}]);

In my controller, API.call() always returns undefined. It seems that responseData is outside the scope of the callback functions. What am I not understanding about JavaScript scope?

Philip
  • 1
  • 3
  • 1
    $http is async. Your function call()'s `return responseData;` is executed before your seccess or failure callbacks are called. – Ken May 10 '17 at 19:33
  • You could return the call you are making to http and have the success and failure callbacks return `responsedata` – Ken May 10 '17 at 19:34
  • Your understanding of scope is fine. It's a problem with execution order. – Bergi May 10 '17 at 19:35
  • I just noticed that @Bergi, please just disregard all that, I just edited it in. – Travis J May 10 '17 at 19:40
  • @Ken I got it working with your suggestion. Much appreciated. I admit I am a bit of a noob with the concept of asynchronous execution. You really cleared it up for me, thanks! – Philip May 10 '17 at 20:24

0 Answers0