簡體   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