Angularjs: set custom header on $ resource before calling action?

I have the following definition of $ resource:

angular.module("MyApp").factory("account", ["$resource",
function ($resource) {

    var userResource = $resource("http://localhost/api/account/:id",
        {
            id: "@id"
        },
        {
            register: {

                method: "Post",

            }
    );

    return userResource;
}]);

      

Before every call to user.query, get, register, etc. I need to set a custom header which is an authorization header with an access token.

Note that setting the header globally will not work, as the access token may expire and be updated with a new one before each call to the $ resource and therefore the authorization header will change. Also I need to set the title for certain actions only. For example, I don't need this in a save action.

I read this article:

http://nils-blum-oeste.net/angularjs-send-auth-token-with-every-request/

which, by the way, is linked to several stackoverflow posts. But this is not what I want as it sets the token in the action data and I need it in the header.

+3


source to share


1 answer


for me it was just a syntax problem - this post helped me.

Dynamic resource headers



.factory("ResourceService", function() { 
   return { 
     Token: function(token){
        return $resource("someurl/checktoken", {}, {
           validateToken: {method:"POST", params: {}, headers: {"MY-AUTH-TOKEN": token}}
        });
 }}})

      

0


source







All Articles