2

The following approach does not work:

angular.module('myApp.myModule').factory('MyResource', function($resource, $cookies) {

    var token = $cookies.get('token');
    var user = $cookies.get('username');

    console.log ("Token: "+token+" User: "+user);

    return $resource(
        'http://my-rest-api/whatever/:id',
        {
            headers: {
            'token': token,
            'user': user
            }
        }
)});

Console shows the correct data, but they were not sent..

That's the part somewhere in the related Controller (excerpt):

var getEntryOne = MyResource.get({ id: 1 }, function() {
    console.log("Result: "+getEntryOne);
});

I get the "Message: Token invalid", I see the request-http-headers in firebug, they were not setted.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299

1 Answers1

1

You are setting headers for get request then it should be there in get option of $resource

$resource('http://my-rest-api/whatever/:id',{},{
    get:{
        method:"GET",
        headers:{
            'token': token,
            'user': user
        } 
    },
});

If you wanted to add this header information to each request, then you could have http inteceptor which will be add header information on each request.

app.service('MyResourceInterceptor', ['$cookies', function($cookies) {
    var token = $cookies.get('token'),
        user = $cookies.get('username'),
        service = this;
    service.request = function(config) {
        config.headers['token'] = token;
        config.headers['user'] = user;
        return config;
    };
}]);

app.config([ '$httpProvider',   function($httpProvider) {
    $httpProvider.interceptors.push('MyResourceInterceptor');
}]);
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Yes, I know that, but it should work for all methods. I don't want to write it each time at each method. –  Dec 08 '15 at 18:55
  • @Vienna then you should go for `httpInterceptor` & in that you could place this header on each request.. – Pankaj Parkar Dec 08 '15 at 18:56
  • How can I use it in my case above? –  Dec 08 '15 at 19:01
  • @Vienna Glad to help you..Thanks :) – Pankaj Parkar Dec 08 '15 at 19:26
  • What's the scope of $httpProvider.interceptors - will it apply to the entire AngularJS app, or just a single $resource? – Tom Söderlund Nov 25 '17 at 09:51
  • 1
    @TomSöderlund `Injectors` are singleton in AngularJS application, throughtout the application it same same injector instance. So that's why these interceptors are applicable all over $http call. If you want to specifically apply some changes to request/response just use `transformRequest`/ `transformResponse` based on your need – Pankaj Parkar Nov 25 '17 at 11:09