I am working with the $http in angularjs1.4.7.
I need to separate my controllers from any $http requests. So i created a service as follows:
app.service('MyService', function($http, $q, $rootScope) {
this.getcustomers = function() {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'http://call/to/rest/api'
}).then(function successCallback(response) {
deferred.resolve(response.data);
}, function errorCallback(response) {
deferred.reject(error);
});
return deferred.promise;
};
});
Then in my controller i call that service as follows:
app.controller('registerationCtrl', ['$scope', '$http', 'MyService', '$location', function($scope, $http, MyService, $location) {
$scope.custlst = [];
$scope.getcustomers = function() {
var x = MyService.getcustomers().then(function(data) {
$scope.custlst = data;
}, function(err) {
alert(err);
});
}
}]);
Now, the above is not working it gives me a ReferenceError of error now defined and points to the errorCallback function in the service.
Question 1: What is wrong with the script?
Question 2: Is it important to use $q? Keeping in mind that the server can be slow.
Thanks.
errorvariable insideerrorCallbackis not defined, hence the error... You probably meant to dofunction errorCallback(error) {...}instead offunction errorCallback(response) {...}. And no, you didn't need to use$q- you could have just returned the promise already generated by$http