[英]AngularJS and Typescript - Injecting Services
我一直在写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;
});
}
}
}
}
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]);
他们似乎都工作。 您是否必须明确定义服务的注入?
在缩小代码时,您确实需要为服务或任何其他角度实体(提供者,工厂,控制器等)注入依赖关系。 在非缩小代码中,两种方法都可行。
考虑一下构造函数: -
constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
}
案例1 [显式依赖注释]: -
app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
缩小也没有问题,因为即使缩小器改变$http
来说a
和$q
说b
它仍然可以工作,因为angular将在内部使用annotate从你提供的定义服务的数组中派生依赖。
案例2 [隐含依赖]: -
app.service('customerDataService', Application.Services.CustomerDataService);
在这种情况下,如果$http
更改为a
和$q
更改为b
angular将在实例化您的服务时查找aProvider和bProvider,并且最终您的应用程序将在使用缩小文件运行时失败,因为没有列出作为依赖项角度解析器必须解析方法定义和方法的参数名称以发现依赖关系。
注入依赖关系的另一种方法是使用在函数(cTor)上定义的$inject
属性(不在实例上)。 你可以这样做: -
export class CustomerDataService implements ICustomerDataService {
static $inject = ['$http', '$q']; //<-- Inject here
constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
}
....
只是: -
app.service('customerDataService', Application.Services.CustomerDataService);
列出您的依赖项有时也有助于为注入的服务参数名称使用备用名称。 如果你不想做所有这些并仍然使用minifier你可以使用ng-annotate库。
对于angular 1.3 rc,有一个名为strict-di的选项,您可以在rootElement
上指定该选项,以强制对任何服务或将在应用程序生命周期中实例化的任何角度实体进行显式注释依赖注入。 如果使用此选项,则在实例化期间未明确注释的任何服务都将失败。
两者都是一样的但是在你的第一个选项缩小时你的代码将被破坏,因为缩小逻辑将改变依赖的名称所以在第二个选项中你给出一个依赖的数组,缩小算法不会触及
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.