I wonder how to simulate a promise $http when I know that the request will fail on the server-side. Here is my code:
if ( !ng.isString(email) ) {
var promise = $q.defer().promise;
$q.reject();
return promise;
}
return $http( {
method : "PUT",
url : "//localhost/update" ,
data : { data: email }
})
// Success handler
.success(response){ return response})
// Error handler
.error(errorMsg){ return errorMsg});
You can use resolve and reject to control the flow of your data:
Let's say you have a service like this:
var app = angular.module("mymodule.services", []);
app.factory("HttpRequest", ['$q', '$http', function(q, http) {
var deferredData = q.defer();
http.get('http://your-server.local/data.json').success(function(data) {
//success, resolve your promise here
deferredData.resolve(data);
}).error(function(err) {
//error, use reject here
deferredData.reject(err);
});
return {
get: function() {
return deferredData.promise;
}
};
}]);
The service can then be used as such:
var app = angular.module("mymodule.controllers", ['mymodule.services']);
app.controller("MyCtrl", ['HttpRequest', '$scope', function(res, scope) {
//the "then"-method of promises takes two functions as arguments, a success and an erro callback
res.get().then(function(data) {
//first one is the success callback
scope.data = data;
},
function(err) {
scope.err = err;
});
}]);
You can handle the error in the second callback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With