AngularJS和Typescript - 注入服务

Sam*_*Sam 10 javascript angularjs typescript angularjs-service

我一直在写AngularJS应用程序已经有一段时间了,但是Typescript对我来说是新的,然后将AngularJS添加到Typescript中与我习惯的有点不同.

无论如何,两者有什么区别:

app.service('customerDataService', Application.Services.CustomerDataService);

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);

控制器TS

module Application {
    export module Services {
        export interface ICustomerDataService {
            getCustomer(id: number): ng.IPromise<Models.ICustomer>;
        }

        export class CustomerDataService implements ICustomerDataService {
            constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
            }

            getCustomer(id: number): ng.IPromise<Models.ICustomer> {
                return this.$http.get('data/Customer.json').then((response) => {
                    return response.data;
                });
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

App TS

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

app.value('config', new Application.ApplicationConfig());

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
app.service('customerDataService', Application.Services.CustomerDataService);

app.controller('DefaultController', ['$scope','config', 'customerDataService', Application.Controllers.DefaultController]);
Run Code Online (Sandbox Code Playgroud)

他们似乎都工作.您是否必须明确定义服务的注入?

PSL*_*PSL 17

在缩小代码时,您确实需要为服务或任何其他角度实体(提供者,工厂,控制器等)注入依赖关系.在非缩小代码中,两种方法都可行.

考虑一下构造函数: -

 constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
 }
Run Code Online (Sandbox Code Playgroud)

案例1 [显式依赖注释]: -

app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
Run Code Online (Sandbox Code Playgroud)

缩小也没有问题,因为即使缩小器改变$httpa并且$q说它b仍然有效,因为angular将在内部使用注释从您提供的定义服务的数组中派生依赖关系.

案例2 [隐含依赖]: -

app.service('customerDataService', Application.Services.CustomerDataService);
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果$http更改为say a并且$q更改为bangular将在实例化您的服务时查找aProvider和bProvider,并且最终您在使用缩小文件运行时应用程序将失败,因为没有列出任何依赖项角度解析器将必须解析方法定义和方法的参数名称以发现依赖项.

注入依赖关系的另一种方法是使用$inject函数(cTor)上定义的属性(不在实例上).你可以这样做: -

    export class CustomerDataService implements ICustomerDataService {
        static $inject = ['$http', '$q']; //<-- Inject here

        constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
      }
      ....
Run Code Online (Sandbox Code Playgroud)

只是: -

   app.service('customerDataService', Application.Services.CustomerDataService);
Run Code Online (Sandbox Code Playgroud)

列出您的依赖项有时也有助于为注入的服务参数名称使用备用名称.如果你不想做所有这些并仍然使用minifier你可以使用ng-annotate库.


对于angular 1.3 rc,有一个名为strict-di的选项,您可以在其上指定rootElement对任何服务或将在应用程序生命周期中实例化的任何角度实体执行显式注释依赖注入.如果使用此选项,则在实例化期间未明确注释的任何服务都将失败.