使用 Typescript 在 AngularJS 中注入一个工厂

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26112608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:56:11  来源:igfitidea点击:

Inject a Factory in AngularJS using Typescript

angularjstypescript

提问by Sam

So in plain old Angular, you would inject a Factory like so:

所以在普通的旧 Angular 中,你会像这样注入一个工厂:

(function(angular){
    "use strict";

    var app = angular.module('app', []);
    app.factory('MyFactory', ['$http', function($http) {
    ....
    });
}());

Now using Typescript, I am trying to use the $injectlike so:

现在使用打字稿,我试图使用$inject这样的:

module Services {
    export class MyFactory {
        static $inject = ['$http'];
        constructor(private $http: ng.IHttpService) {
        }
    }
}

var app = angular.module('app', []);

app.factory('MyFactory', Services.MyFactory) //<-- This does not work, never is instantiated.

app.factory('MyFactory', ['$http', Services.MyFactory]); //<-- No deal, it has constructor dependencies

// Seems you have to do this
app.factory('MyFactory', ['$http', ($http) => new Services.MyFactory($http)]);

What is the correct way to inject factories in Angular using Typescript?

使用 Typescript 在 Angular 中注入工厂的正确方法是什么?

回答by Gustav

In this todoMvcexample project they declare factory functions as functions and not as a class.

在这个todoMvc示例项目中,他们将工厂函数声明为函数而不是类。

module Services {
  export function MyFactory($http: ng.IHttpService): string{
     var stuff = "foo";
     return stuff;
  }
  MyFactory.$inject = ["$http"];
}

app.factory("myFactory", Services.MyFactory);

Since directives are factory functions this is the syntax we (in my project) use for directives. Then the return type of the function is ng.IDirective.

由于指令是工厂函数,这是我们(在我的项目中)用于指令的语法。那么函数的返回类型是ng.IDirective.

I also agree with basarat that using .service is better in your case. This is just for reference how you could write a angular factory in typescript.

我也同意 basarat 的观点,在您的情况下使用 .service 更好。这仅供参考如何在打字稿中编写角度工厂。

回答by basarat

app.factory('MyFactory', Services.MyFactory) This does not work, never is instantiated.

app.factory('MyFactory', Services.MyFactory) 这不起作用,永远不会被实例化。

True. This is because the function passed as a second argument (MyFactory) is never called with the newoperator. If you want to use a TypeScript class you mustuse serviceand not factory.

真的。这是因为MyFactory从不使用new运算符调用作为第二个参数 ( )传递的函数。如果你想使用 TypeScript 类,你必须使用service而不是factory.

The usage of the newoperator is the onlydifference between a service and a factory, so there is noreason for you to use a factory. Both are singletons in AngularJS.

new运算符的用法是服务和工厂之间的唯一区别,因此您没有理由使用factory. 两者都是 AngularJS 中的单例。

回答by Pranay Dutta

Take this example as i had created a httpget wrapper

以这个例子为例,因为我创建了一个 httpget 包装器

module portal.services {


export class apiService {


    public getData<T>(url?:string): ng.IPromise<T> {

        var def = this.$q.defer();
        this.$http.defaults.headers.common.token = window.sessionStorage[localStorageNames.bearerToken] || 'UA';
        this.$http.get(this.config.apiBaseUrl + url).then((successResponse) => {

            if(successResponse)
                def.resolve(successResponse.data);
            else
                def.reject('server error');

        }, (errorRes) => {

            def.reject(errorRes.statusText);
        });

        return def.promise;
    }


    static $inject = ['$q','$http', 'config'];

    constructor(public $q:ng.IQService,public $http:ng.IHttpService, public config:interfaces.IPortalConfig) {


    }

}



}


module portal {
   export var app:ng.IModule =angular.module('portal',[]);
    app.service(services);

}