I am pretty new to AngularJS and Javascript. I am creating a app in which I am planning to use one function to do all ajax related operation(factory in angularjs). This function will be only one gateway for all ajax operations. When I return promise as a success it works properly. but returning error promise do not work.
Here is a sample code. I am expecting return of promise in error function if promise fails but it goes to success
var myApp = angular.module('myApp', []);
myApp.controller('FirstController, function($scope, util){
util.doAjax().then(function(response){
// This function is called in both success and error
}, function(err){
// This is never called why ?
});
});
myApp.factory('util, function($http){
return $http({
method: 'GET',
url: 'http://www.example.com'
}).then(function(response){
// This will return success promise
return response;
}, function(err){
// This should return error promise
return err;
});
});
Currently you are directly returning a data from error function, which is chaining the promise and calling it underlying .then method.
While returning an error you have to reject a promise by creating a new custom promise using $q
return $q.reject(err)
Other important thing is, you should create method in a service with name
myApp.factory('util', function($http, $q){
//Exposed method
return {
doAjax : function() {
return $http({
method: 'GET',
url: 'http://www.example.com'
}).then(function(response){
// This will return success promise
return response.data; // returned data
}, function(err){
// return error promise with err object
return $q.reject(err);
});
}
}
});
This way you are not returning a promise.
You must return the $http promise instead like so:
myApp.factory('util', function($http){
return {
ajax: function () {
var httpPromise = $http({
method: 'GET',
url: 'http://www.example.com'
});
httpPromise.then(function(response){
// This will return success promise
// return response;
}, function(err){
// This should return error promise
// return err;
});
return httpPromise;
};
});
And also, return inside promise resolutions are not needed, you can use it for loggin and stuff but it doesn't require a return value because it is the resolution it self.