I have created a Typescript Class (see code...) that I want to use as an HTTP injector. It is being added to the Angular module as a service (not a factory). I have noticed a few issues.
- When the class defines the 'request' and 'response' functions with capital letters, the injector does not work (theses functions are never called). When defined with lowercase letters, they are called.
- When the functions are correctly called, the "this" object refers to the global window and not the object.
I solved the problem by creating true factory (see code...) and adding it to the Angular module as a Factory.
However, I would love to understand why this is happening. Any thoughts?
module KernEquity.Angular
{
export interface IHttpInjector
{
request(request: ng.IRequestConfig): ng.IRequestConfig;
response(response: any):any;
}
export function TokenInjectorFactory($rootScope:KernEquity.Angular.IRootScope):IHttpInjector
{
var injector = {
request: function (config:ng.IRequestConfig)
{
if ($rootScope.IsAuthenticated)
{
config.headers["Authorization"] = this.$rootScope.BearerToken.GetTokenHeader();
}
return config;
},
response: function (response:any)
{
return response;
}
}
return injector;
}
export class TokenInjectionService
{
$rootScope: KernEquity.Angular.IRootScope;
static $inject = ["$rootScope"];
constructor($rootScope:KernEquity.Angular.IRootScope)
{
this.$rootScope = $rootScope;
}
request(config: ng.IRequestConfig):ng.IRequestConfig
{
this.$rootScope = null;
return config;
}
Response(response: any):any
{
return response;
}
}
}
Notice the "request" vs. "Response". The former will be called. The latter will not.
JavaScript is case sensitive.
Response
is not the same asresponse
. You need to keep it lowercase.You cannot use a
class
(directly at least) for stuff that angular expects to be a factory as factories are not called withnew
. Therefore angular calls the provided function asTokenInjectionService($rootScope)
instead of the expectednew TokenInjectionService($rootScope)
. Simplest answer: just use a function.