【问题标题】:Angular with Typescript: HTTP Injector Factory vs. ServiceAngular 与 Typescript:HTTP 注入器工厂与服务
【发布时间】:2015-06-22 08:18:25
【问题描述】:

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

  1. 当类用大写字母定义“请求”和“响应”函数时,注入器不起作用(这些函数永远不会被调用)。当用小写字母定义时,它们被调用。
  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;
        }
    }
}

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

【问题讨论】:

    标签: angularjs typescript angular-http-interceptors


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2016-12-12
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多