0

Recently I found a TokenHandler that allows me to send a token on every rest api request. You can find a detailed description here: http://nils-blum-oeste.net/angularjs-send-auth-token-with-every--request/#.UXtYlbVTDIX

I am facing an issue implementing this handler in my project. My project is dealing with a couple of resources, let me just talk of Post and Author. What I am currently doing is:

angular.module('PostService', ['ngResource']).factory(....
angular.module('AuthorService', ['ngResource']).factory(....

And I wrap it up in my main app module

var app = angular.module('myApp', ['PostService', 'AuthorService']);

My question is, where do I setup the TokenHandler? It has to be assigned to a module right? I would assign it to e.g. PostService but I would not be able to use it in AuthorService as a result?

As a consequence of that I have another question. Is it possible to wrap multiple resources in one service like:

angular.module('RestService', ['ngResource']).factory(['Post', 'Author'],...
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601

1 Answers1

2

Just follow the guidelines in the quoted article, declaring the TokenHandler service:

angular.module('TokenHandler').factory('TokenHandler', function() {...

and configuring each service you need to assign the token to in the following way:

angular.module('AService', ['ngResource', 'TokenHandler']).factory('AService', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
    var resource = $resource("http://...", {
        ...
    }, {
        get: {
            method:'GET', 
            params:{
                action:'get'
            }, 
            isArray:false
        },
        ...
    });

    resource = tokenHandler.wrapActions( resource, ["get", ...] );

    return resource;
}]);

You only wrap the actions that require the token to be sent. As to your second question, it wouldn't be a good programming practice and, anyway, a factory just returns one object.

remigio
  • 4,101
  • 1
  • 26
  • 28