javascript - How can I retrieve HTTP status codes using Angular's $q promises? -
i have within code makes $http.post
end, , of course things can go wrong. if use below syntax within angular:
$http.post(url).success(function(data, status, headers, config)) .error(function(data, status, headers, config));
if there error, can retrieve error code using status
, handle within function defined in error()
. however, if instead take approach (which 1 in fact using):
var deferred = $q.defer(); $http.post(url).success(deferred.resolve).error(deferred.reject); return deferred.promise;
with second syntax, have of ajax calls within separate servicejs
directory, , can handle successes or errors on case case basis. instance, if second snippet service.myfunction()
in code need would:
service.myfunction().then(function() {}, function(data, status, headers, config) {});
however, if use code block, status
, headers
, config
undefined. question how can retain syntax still retrieve error code?
as added reference, end c# web api project, return errors using return badrequest();
or like.
try this:
myfunction(){ var deferred = $q.defer(); // can use .then() instead of .success or .error $http.post(url).then(function(successresponse){ var data = successresponse.data; var status = successresponse.status; ... deferred.resolve(successresponse); }, function(failureresponse){ var status = failureresponse.status; var config = failureresponse.config; ... deferred.reject(failureresponse); }); return deferred.promise; }
Comments
Post a Comment