Reputation: 395
Hi I am trying to pull my angular js factory data to my controller, please have a look if there is any issue.
factory.js
.factory('History', ['$http', '$q', function ($http, $q) {
function history () {
// angular.extend(SearchOptions.getDefaults(), params, options);
var deferred = $q.defer();
$http({
method: 'GET',
url: '/res/orders/' + 31536427 + '/history-group'
})
.success(function (res) {
// console.log(res);
})
.error(function (err) {
// TODO error handler
deferred.reject(err);
});
return deferred.promise;
}
return {
history: history
};
}]);
controller.js
.controller('HistoryCtrl', ['$scope', '$state', '$stateParams', 'History', function($scope, $state, $stateParams, History) {
History.history().then(function(res) {
console.log(res);
$scope.history = res.body;
console.log($scope.history);
}, function(err) {
// TODO error handler
console.log(err);
})
.finally(function(err) {
});
}]);
Upvotes: 0
Views: 51
Reputation: 3266
The issue with your code is you are not resolving the promise after getting the data in the success callback function. Resolve it as shown below in the .success
callback function :
deferred.resolve(res);
Few points to improve your code:
$http
service in Angular by default returns a promise. Hence, you don't have to explicitly construct a promise
using $q
which is an anti pattern (Deferred anti-pattern). Just returning $http
object from the service itself will do the
job. Doing return $http()
is equivalent to return deferred.promise()
in your code.
.success
and .error
callbacks are deprecated in the latest version(1.6) of AngularJs
(Deprecation Notice). The disadvantage of using these is that they are not chainable as they ignore return values. Hence, it is better to use .then
instead.
Applying above changes, your service can be refactored to below :
.factory('History', ['$http', function ($http) {
function history () {
return $http({
method: 'GET',
url: '/res/orders/' + 31536427 + '/history-group'
})
.then(successCallback, errorCallback);
}
function successCalback (res) {
return res;
}
function errorCalback (err) {
return err;
}
return {
history: history
};
}]);
Upvotes: 1
Reputation: 93
You need to pass the response in the success function in the 'History' factory as below:
.success(function (res) {
// console.log(res);
deferred.resolve(res);
})
Upvotes: 3