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.
You must add an interceptor inside your resource declaration. Like this:
Usage:
IMO status code should have been provided by default. There is an issue for this https://github.com/angular/angular.js/issues/8341
I think the right answer is a combination of Bardiel's and Ara's answers.
After adding an interceptor inside your resource declaration. Like this:
Use it as below:
You can get response status like this:
I had faced the similar problem.I looked into the angular lib and added a few lines to have status returned in the response itself.In this file,find where promise is being returned.
Replace code block starting with
with the following
or you can add this line
and then access status in code like reponse.status.Though,this is kind of hack but worked for me.I also had to make changes in the minified version.
You can use the promiss callbacks
then
,catch
andfinally
after the$resource
call.For example. If you want to catch an error after a call, you would do something like this:
The
response
object will havestatus
and thestatusText
properties.status
being an integer status code andstatusText
the text. You'll also have thedata
property containing the server response.edit: as suggested, it was
response.status
I agreed
responseHeaders()
function will only return response's header,but you can custom it and it's useful anyway.1.
To solve you problem. With the following:(
$$service
is my $resource instance.)In this way,u can only catch
status,statusText,timeout,method,headers(same with responseHeaders)
in ERROR response.2.
If you want to see response details in success response,I used a interceptor like this:
and then add interceptor to module: