繁体   English   中英

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

[英]Angular with Typescript: HTTP Injector Factory vs. Service

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

  1. 当该类用大写字母定义“ request”和“ response”功能时,注入器将不起作用(永远不会调用这些功能)。 用小写字母定义时,将调用它们。
  2. 正确调用函数后,“ this”对象是指全局窗口,而不是对象。

我通过创建真正的工厂(参见代码...)并将其作为工厂添加到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;
        }
    }
}

注意“请求”与“响应”。 前者将被称为。 后者不会。

注意“请求”与“响应”。 前者将被称为。 后者不会。

JavaScript区分大小写。 Responseresponse 您需要将其保持小写。

正确调用函数后,“ this”对象是指全局窗口,而不是对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM