user2227400
user2227400

Reputation:

How to set default header values in Angular Resource?

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.

Upvotes: 2

Views: 2910

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

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');
}]);

Upvotes: 1

Related Questions