我编写 AngularJS 应用程序已有一段时间了,但 Typescript 对我来说是新手,然后将 AngularJS 添加到 Typescript 与我习惯的有点不同。
不管怎样,两者有什么区别:
app.service('customerDataService', Application.Services.CustomerDataService);
和
app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
Controller 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;
});
}
}
}
}
应用程序技术分析
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]);
它们似乎都有效。您是否必须明确定义服务的注入(inject)?
最佳答案
在缩小代码时,您确实需要为服务或任何其他 Angular 实体(提供者、工厂、 Controller 等)注入(inject)依赖项。在非缩小代码中,是的,这两种方法都可以。
考虑构造函数:-
constructor(private $http: ng.IHttpService, private $q: ng.IQService) {
}
案例一【显式依赖注解】:-
app.service('customerDataService', ['$http', '$q', Application.Services.CustomerDataService]);
缩小也没有问题,因为即使缩小器将 $http
更改为 a
并将 $q
更改为 b
它仍然有效,因为 Angular 将在内部使用注释从您提供的定义服务的数组中派生依赖项。
案例 2 [隐式依赖]:-
app.service('customerDataService', Application.Services.CustomerDataService);
在这种情况下,如果 $http
更改为 a
并且 $q
更改为 b
angular 将在实例化您的服务时查找 aProvider 和 bProvider,最终您的应用程序将在使用缩小文件运行时失败,因为没有列出任何依赖项 angular 解析器将必须解析方法定义和方法的参数名称以发现依赖项。
另一种注入(inject)依赖项的方法是使用在函数 (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);
有时列出您的依赖项也有助于为注入(inject)的服务参数名称使用备用名称。如果你不想做所有这些并且仍然让你的代码与 minifier 一起工作,你可以使用 ng-annotate 图书馆。
对于 angular 1.3 rc,有一个名为 strict-di 的选项您可以在 rootElement
上指定它,以对将在您的应用程序生命周期中实例化的任何服务或任何 Angular 实体强制执行显式注释依赖注入(inject)。如果您使用此选项,则任何未明确注释的服务等都将在实例化期间失败。
关于javascript - AngularJS 和 Typescript - 注入(inject)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109895/