Custom Headers per request on an Angular $resource

Posted by Matt Bryson on 09-Sep-2014 14:50:14
Find me on:

You can set custom headers for every request, such as 'Authorization', like:

$http.defaults.headers.common.Authorization = 'Bearer 12345abcde';

And you can set them at a `Resource` level, like:

app.factory('My_Resource', ['$resource', function($resource) {
return $resource( '', null, {
get': {headers: {'Authorization': 'Bearer 12345abcde' }},

But how do you set the header per request, and pass a value into the request?

In the end we went for this solution...

app.factory('MyResource', ['$resource', function($resource) {
var MyResource = {
get:function(params, success, error) {
var res = $resource( '', null, {
'get' : { method:'GET', headers: {'Authorization': 'Bearer ' + params.token }}

return res.get({}, success, error);

return MyResource;

//Then later...
MyResource.get({id:1, token:'12345abcde'}, success, error );

By no means a complete solution, but you get the idea.

You could pass the headers as a second parameter, and then you can just proxy the request object through to the actual resource.

You could also think about extending the `Resource` object, so you don't have to proxy all the REST verb methods, but the above is all we needed.


Topics: Angular

About the author

Matt Bryson is an experienced systems engineer with over 15 years Development and Systems Operations experience.

NEW - Free eBook

Transforming your eDetail process. Click below to download the eBook.

New Call-to-action

Subscribe to Email Updates