Reputation: 97
I have created a factory in my AngularJS application which is used to bring in refreshed data from server after a delete has been performed on one or more elements of the list.
var myApp = angular.module('app');
myApp.factory('mvListRefresher', function($http) {
return {
refreshCourses : function() {
var list = new Array();
$http.get('/api/courses').then(function(response) {
console.log('got refreshed lists');
console.log(response.data);
list = response.data;
}, function(error) {
console.log('error in retreiving fresh lists');
console.log(error);
});
console.log('Displaying list of courses');
console.log(list);
if(list.length != 0) {
return list;
}
}
}
});
I'm calling this factory in one of my controllers by calling
$scope.courses = mvListRefresher.refreshCourses();
But I'm getting an empty list, i.e I'm not getting any return value at all. In my factory function I observed that the line
console.log(list);
always prints out an empty array, however the line
console.log(response.data);
which is inside the success callback prints out the full list of objects correctly. I don't know how this is happening. I'm relatively new to AngularJS's promises and it's asynch methods and architecture. Kindly help me out. If you need any more info i'll provide it. I've done the entire app using MEAN. Thanks in advance!
Upvotes: 1
Views: 3149
Reputation: 12721
$http
requests are asynchronous by nature so at the point you're returning list
, the request is not complete yet. You can read more about the general concepts of asynchronicity in JavaScript in this response: https://stackoverflow.com/a/14220323/704894
What you should do instead is return a Promise of list:
myApp.factory('mvListRefresher', function($http) {
return {
refreshCourses: function() {
return $http.get('/api/courses').then(function(response) {
return response.data;
});
}
};
});
$http
methods return promises of results. Then you can use this function in the following way:
mvListRefresher.refreshCourses().then(function (list) {
$scope.courses = list;
});
You can read more about it in the $http documentation.
Upvotes: 4