I'm having trouble with callbacks and asynchronous requests in angular. I created a service to fetch the data which uses callbacks (once the calls_left hits 0, callback is called). I inject my service inside my controller and then call the getMInterval on my service (metr.getMInterval) which should initialize the data (pTypes in this case) and wait till it is finished. The problem is that pTypes logs first as empty Array []. Any ideas?
Service:
angular.module('mService', ['config']).service('metr', function($http, $window, $rootScope, $location, config) {
var pTypes = [];
var intervalData = {};
function fetchMInterval(callback) {
var calls_left = 1;
var onComplete = function() {
calls_left--;
if (calls_left == 0) {
console.log("finished retrieving data from api");
if (callback) callback();
}
};
var url = 'fetch_data_from_this_url';
$http({
method: 'GET',
url: url
}).then(function success(response) {
console.log(response);
var data = JSON.parse(response.data.split(config.DELIMITER)[1]);
intervalData = data["Data"];
pTypes = metrIntervalData["pTypes"];
onComplete();
}, function error(response) {
alert("Failed to fetch info from " + url + "! " + response.status);
onComplete();
});
}
retu {
getMInterval:function() {retu fetchMInterval();},
getPTypes:function() {retu pTypes;},
}
Controller:
app.controller('mController', function($scope, $filter, metr, config) {
metr.getMInterval();
$scope.pTypes = metr.pTypes();
console.log(metr.pTypes()); //console logs Array []
});
