How to pass headers on the fly to $resource for angularjs

前端 未结 1 393
情书的邮戳
情书的邮戳 2020-12-29 06:53

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({
  u         


        
1条回答
  •  被撕碎了的回忆
    2020-12-29 07:57

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

    0 讨论(0)
提交回复
热议问题