I'm using angular-http-auth to show a login dialog whenever a 401 "unauthorized" response is returned from the server.
Since I'm cool, I also try to deserialize response objects in my services. For example, if a service requests a car
and the response is {make: Honda, model: Civic}
, I try to deserialize that into a Car
object using transformResponse
.
For example:
getCar: function() {
return $http.get('/api/car', {
method: 'GET',
transformResponse: function(data, headers) {
var c = angular.fromJson(data);
return new Car(c);
}
});
}
This doesn't work with angular-http-auth. If the response was a 401 Unauthorized, you'll get a javascript error. It's because angular will try to run that transformResponse
code even if the response was a 401.
It turns out that $http
interceptors (which is what angular-http-auth uses) are run AFTER the transformResponse
code. That's a huge problem, because none of that code in transformResponse
will work if the server response was a 401 (there wouldn't be any data
)
Is this a problem for anyone else? How did you get around it? Am I not to use transformResponse
if I use $http
interceptors?
Late to the party, I know, but to anyone coming here from Google like I did (I also posted this as a comment on a related issue filed with the Angular repo):
I also found it to be confusing that response interceptors run after the
transformResponse
method. I added a method to$http.defaults.transformResponse
. Here is an example from the documentation on how to do that.So, if you need to basically have a response interceptor that runs before the
transformResponse
method, this should do it:If your services or http calls don't have their own response transformer, you're good now.
If your services do have their own
transformResponse
method, they will actually override all default transformers (I found this out after a long read of the documentation), and the above code will not run.To circumvent this, you can follow this example in the docs.