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?