简体   繁体   English

使用Typescript在AngularJS中注入工厂

[英]Inject a Factory in AngularJS using Typescript

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 $inject like so: 现在使用Typescript,我试图像这样使用$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中注入工厂的正确方法是什么?

In this todoMvc example 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. 我也同意basarat使用.service在你的情况下更好。 This is just for reference how you could write a angular factory in typescript. 这仅供参考,如何在打字稿中编写角度工厂。

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 new operator. 这是因为从未使用new运算符调用作为第二个参数( MyFactory )传递的函数。 If you want to use a TypeScript class you must use service and not factory . 如果要使用TypeScript类,则必须使用service而不是factory

The usage of the new operator is the only difference between a service and a factory, so there is no reason for you to use a factory . new运算符的使用是服务和工厂之间的唯一区别,因此您没有理由使用factory Both are singletons in AngularJS. 两者都是AngularJS中的单身人士。

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

}

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

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