Thanks to Andy Jocelyn. I chose his idea to wrap the action of resources. Now the service for the resource is as follows:
.factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) { var resource = $resource('http://localhost:port/todos/:id', { port:":3001", id:'@id' }, { update: {method: 'PUT'} }); resource = tokenHandler.wrapActions( resource, ["query", "update"] ); return resource; }])
As you can see, a resource is determined, first of all, in the usual way. In my example, this includes a custom action called update . Subsequently, the resource is overwritten by returning the tokenHandler.wrapAction() method, which takes the resource and an array of actions as parameters.
As expected, the latter method actually includes actions to enable the authentication token in each request and returns the changed resource. So let's look at the code for this:
.factory('TokenHandler', function() { var tokenHandler = {}; var token = "none"; tokenHandler.set = function( newToken ) { token = newToken; }; tokenHandler.get = function() { return token; };
As you can see, the wrapActions() method creates resource parameters from it and loops through the actions array to call another tokenWrapper() function for each action. At the end, it returns a modified copy of the resource.
The tokenWrapper method first creates a copy of a previously existing resource action. This copy has a trailing underscore. So query() becomes _query() . Subsequently, the new method overwrites the original query() method. This new method wraps _query() , as Andy Hoslin suggested, to provide an authentication token with every request sent through this action.
Itβs good that with this approach, we can still use the predefined actions that come with each angularjs resource (get, query, save, etc.), without the need to redefine them. And in the rest of the code (for example, in controllers) we can use the default action name.