I have created three services, OpenApi, SecureApi, and TokenHandler. I want to use TokenHandler Service from SecureApi Service. When authentication will happen controller code will set token in TokenHandler.Set() method. and I want SecureApi to cal tokenHandler.get() as below. Is it Possible. Right now I am getting below error:-
EDIT:- fixed below error (updated the code below too, but my token is still not getting through as part of header :()
Unknown provider: tokenHandlerProvider <- tokenHandler <- SecureApi
Code:-
/* Services */
angular.module('MyApp.services', ['ngResource'])
.factory('OpenApi', function ($resource) {
var openApi = $resource(
'/api/:controller/:id',
[],
{
postLogOn: { method: 'POST', params: { controller: 'Account' } },
postCustomer: { method: 'POST', params: { controller: 'Employee' } }
}
);
return openApi;
})
.factory('TokenHandler', function () {
var tokenHandler = {};
var token = "none";
tokenHandler.set = function (newToken) {
token = newToken;
};
tokenHandler.get = function () {
return token;
};
return tokenHandler;
})
.factory('SecureApi', ['$resource', 'TokenHandler', function(res, tokHandler) {
var secureApi = $resource(
'/api/:controller/:id',
[],
{
getInsightCustomer: { method: 'GET', params: { controller: 'MyCustomer' }, headers: {Authorization_Token: tokenHandler.get()} }
}
);
return secureApi;
}]);
I got answer of this in AngularJS googlegroups:-
https://groups.google.com/forum/?hl=en&fromgroups=#!topic/angular/jfttVnvga9M
It was a syntax error in above code.
You TokenHandler service has an upper case T but your SecureApi service is "requesting" tokenHandler with a lower case t. Generally it is better - and essential if you are going to minimize you js to use the array injection format, which also then allows you to use anything you like as a parameter name for that service. For example:
.factory('SecureApi', ['$resource', 'TokenHandler', function(res, tokHandler) { ... }]);