18

Right now, the only way that I know for setting tokens in headers dynamically for an angularjs call is via $http like so:

return $http.get({
  url: 'https://my.backend.com/api/jokes',
  params: {
    'jokeId': '5',
  },
  headers: {
    'Authorization': 'Bearer '+ $scope.myOAuthToken
  }
});

But I want to figure out how to pass this via $resource, here's some pseudo-code that doesn't work:

...
.factory('myFactory',
  ['$resource',
    function($resource){
      return {
        jokes: $resource('https://my.backend.com/api/jokes', null, {
          query: {
            method: 'GET'
          }
        })
      };
    }
  ]
);
...
return myFactory.jokes.query({
  'jokeId': '5',
  'headers': {
    'Authorization': 'Bearer '+ $scope.myOAuthToken
  }
});

How can I pass headers on the fly to $resource for angularjs?

1 Answer 1

36

I don't think this can be done the way you are trying, as the config object is not available on action method. But the action config method has it. So what you can do is, rather than returning resource directly, create a function that takes a parameter the authorization token and then construct the resource and return.

return {
    jokes: function (token) {
        return $resource('https://my.backend.com/api/jokes', null, {
            query: {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                }
            }
        })
    }
};

Then call the service function as:

myFactory.jokes($scope.myOAuthToken).query({'jokeId': '5'});
Sign up to request clarification or add additional context in comments.

1 Comment

I tried it out, worked like a charm! Thanks @Chanermani! Sample Code: sample.factory('Restricted', ['$resource', function($resource){ return { createRestrictedResource: function(token) { return $resource('/api/v1/restricted', null, {query: {headers: {'Authorization': 'Bearer ' + token}}}); } } }]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.