Angular -http-auth with $ http transformResponse

I use angular-http-auth to show a login dialog when a 401 "unauthorized" response is returned from the server.

Since I'm cool, I am also trying to deserialize the response objects in my services. For example, if a service asks for cara response {make: Honda, model: Civic}, I try to deserialize it into an object carusing transformResponse.

For instance:

getCar: function() {
    return $http.get('/api/car', {
        method: 'GET',
        transformResponse: function(data, headers) {
            var c = angular.fromJson(data);
            return new Car(c);
        }
    });
}

This does not work with angular-http-auth . If the response was unauthorized 401, you will receive a javascript error. This is because angular will try to run this code transformResponseeven if the response was 401.

, $http ( angular-http-auth) transformResponse. , transformResponse , 401 ( data)

- ? ? transformResponse, $http?

+4
2

, , , Google, ( Angular):

, , transformResponse. $http.defaults.transformResponse. , .

, , transformResponse, :

'use strict';

angular.module('app')
  .run(function ($http) {
    $http.defaults.transformResponse.push(function (data, headers) {
      // do stuff here before the response transformation

      // Be sure to return `data` so that the next function in the queue can use it.
      // Your services won't load otherwise!
      return data;
    });
  });

http- , .

transformResponse, ( ), .

, .

+3

, transformResponse. transformResponse, $http-.

angular-http-auth, , , HTTP- .

, OP:

Plunker

services.factory('HttpCarService', function($resource, $q) {
  var resource = $resource('/api/car');

  return {

    getCar: function() {

      var deferred = $q.defer();
      var car = null;

      var successCallback = function(data, status, headers, config) {
        var c = angular.fromJson(data);
        car = new Car(c);
        deferred.resolve(car);
      };

      var errorCallback = function(data, status, headers, config) {
        deferred.reject("something wrong");
      };

      var result = resource.get(successCallback, errorCallback);
      return deferred.promise;
    }
  };

});

, data - .

$http , . $resource url, getCar() $resource.get().

+1

All Articles