Angular 使用 Typescript:HTTP 注入器工厂与服务

Angular with Typescript: HTTP Injector Factory vs. Service

我创建了一个 Typescript Class(参见代码...),我想将其用作 HTTP 注入器。它作为服务(不是工厂)被添加到 Angular 模块。我注意到了一些问题。

  1. 当class用大写字母定义'request'和'response'函数时,注入器不工作(永远不会调用这些函数)。当用小写字母定义时,它们被称为。
  2. 正确调用函数时,"this" 对象指的是全局 window 而不是对象。

我通过创建真正的工厂(见代码...)并将其作为工厂添加到 Angular 模块来解决问题。

不过,我很想知道为什么会这样。有什么想法吗?

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;
        }
    }
}

注意 "request" 与 "Response"。前者会被调用。后者不会。

Notice the "request" vs. "Response". The former will be called. The latter will not.

JavaScript 区分大小写。 Responseresponse 不同。你需要保持小写。

When the functions are correctly called, the "this" object refers to the global window and not the object.

您不能将 class(至少直接)用于 angular 期望成为 factory 的东西,如 factories 未使用 new 调用。因此 angular 将提供的函数调用为 TokenInjectionService($rootScope) 而不是预期的 new TokenInjectionService($rootScope)。最简单的答案:只需使用一个函数。