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.
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.
Notice the "request" vs. "Response". The former will be called. The latter will not.
JavaScript is case sensitive. Response
is not the same as response
. You need to keep it lowercase.
When the functions are correctly called, the "this" object refers to the global window and not the object.
You cannot use a class
(directly at least) for stuff that angular expects to be a factory as factories are not called with new
. Therefore angular calls the provided function as TokenInjectionService($rootScope)
instead of the expected new TokenInjectionService($rootScope)
. Simplest answer: just use a function.