I know questions like this have been asked before with Angular, unfortunately I can't get any of those solutions to work with my specific implementation so I am asking here.
I have a function scope.getOrders()
here:
$scope.lastOrderFetch,$scope.orders;
$scope.getOrders = function(){
if(moment().diff(moment($scope.lastOrderFetch))>5000||$scope.lastOrderFetch==null){
$http({
method: 'GET',
url: 'http://www.example.com/getOrders',
}).then(function successCallback(html) {
$scope.orders = html.data;
$scope.lastOrderFetch = new Date();
return html.data;
});
}
else{
return $scope.orders;
}
};
I simply want the orders from the backend to popuplate a variable here:
var orders = $scope.getOrders();
Which is in another function. I gather my problem is orders
is always undefined because it is trying to assign to it while $http
is still working it's magic, and it is async so the $http
data is not available right away.
I also gather I am supposed to use a service and then a promise or something, but my issue is that the $http should only fire based on a conditional in the controller. Also a lot of solutions mix callbacks and promises so I'm not sure what to do here. Also, doesn't $http itself return a promise? I'm not sure I need a service which is why I'm posting here to see how I would do this.
Any help would be appreciated.