1

this should be quite easy, but in the end is not working :(. We use Angular 1.4.3, and we try to add an Authorization header value before some API calls.

Long story short, there is a factory:

angular.module('xxx').factory('factory', function ($resource, addBasicAuth) {
   return $resource(baseUrl, {}, {
      query: {method: 'GET', isArray: true, transformRequest: addBasicAuth},
      ...
   });
});

And the addBasicAuth goes as follows:

angular.module('xxx').factory('addBasicAuth', function ($rootScope) {
    return function (data, headersGetter) {
        var user = ($rootScope.user);
        headersGetter().Authorization = 'Basic ' + Base64.encode(user.username + ':' + user.password);
        return angular.toJson(data);
    };
});

And in theory all should work fine, but for the reason I do not understand, the requestHeader is untouched (checked in Developers Tools/Network - Chrome).

What am I doing wrong? Thanks!

Atais
  • 10,857
  • 6
  • 71
  • 111

1 Answers1

1

my colleague helped me out with a following solution;

instead of transformRequest we use headers and it goes like this:

angular.module('xxx').factory('factory', function ($resource, addBasicAuth) {
   return $resource(baseUrl, {}, {
      query: {
         method: 'GET',
         isArray: true,
         headers: addBasicAuth()
      },
      ...
   });
});

and the addBasicAuth is now a factory function:

angular.module('xxx').factory('addBasicAuth', function ($rootScope) {
   return function () {
      var user = ($rootScope.user);
      return {'Authorization': 'Basic ' + Base64.encode(user.username + ':' + user.password)};
   };
});

Works like a charm.

Atais
  • 10,857
  • 6
  • 71
  • 111