Using ngResource
in AngularJS 1.2rc(x), how do I get the status code now?
RestAPI.save({resource}, {data}, function( response, responseHeaders ) { });
where RestAPI
is my ngResource
.
The response has the $promise
object and the resource returned from the server but not a status anymore. The responseHeaders()
function only has a status if the server injects the status code into the header object, but not the true returned status code. So some servers may serve it and some might not.
Use HttpResponse. getStatusLine() , which returns a StatusLine object containing the status code, protocol version and "reason".
Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.
$http is an AngularJS service for reading data from remote servers.
An HTTP status code is a server response to a browser's request. When you visit a website, your browser sends a request to the site's server, and the server then responds to the browser's request with a three-digit code: the HTTP status code.
You can use the promiss callbacks then
, catch
and finally
after the $resource
call.
For example. If you want to catch an error after a call, you would do something like this:
RestAPI.save({resource}, {data}, callbackFunction).$promise.catch(function(response) { //this will be fired upon error if(response.status == 500) alert('Something baaad happend'); }).then(function() { //this will be fired upon success });
The response
object will have status
and the statusText
properties. status
being an integer status code and statusText
the text. You'll also have the data
property containing the server response.
edit: as suggested, it was response.status
You must add an interceptor inside your resource declaration. Like this:
var resource = $resource(url, {}, { get: { method: 'GET' interceptor: { response: function(response) { var result = response.resource; result.$status = response.status; return result; } } } });
Usage:
resource.get(params, function(result) { console.log(result.$status) });
IMO status code should have been provided by default. There is an issue for this https://github.com/angular/angular.js/issues/8341
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