问题描述
我使用AngularJS和打字稿。我想用一个打字稿类,这样实现一个AngularJS服务:
I am using AngularJS and TypeScript. I want to implement an AngularJS service using a Typescript class, like this:
class HelloService {
public getWelcomeMessage():String {
return "Hello";
}
}
angular.module('app.services.helloService', []).factory('helloService', () => {
return new HelloService();
});
这编译为下面的JavaScript code:
This compiles to the following javascript code:
var HelloService = (function () {
function HelloService() {
}
HelloService.prototype.getWelcomeMessage = function () {
return "Hello";
};
return HelloService;
})();
angular.module('app.services.helloService', []).factory('helloService', function () {
return new HelloService();
});
这与污染变量HelloService的,我显然不希望全局命名空间。 (使用Chrome的控制台,我验证了HelloService的是一个对象。)我怎样才能解决/避免这个问题?
This pollutes the global namespace with the variable HelloService, which I obviously don't want. (Using Chrome's console I verified that HelloService was an object.) How can I solve/avoid this problem?
我尝试了很明显的:
angular.module('app.services.helloService', []).factory('helloService', function () {
class HelloService { ...}
return new HelloService();
});
但是这给了我一个编译错误(意外令牌。预计'声明')。
but that gives me a compile error ("Unexpected token; 'statement' expected.").
一个可行的办法,我能想到用打字稿的进口和出口在某种程度上,这反过来将使用RequireJS的。这可能会定义一个函数内包裹HelloService的,从而避免了HelloService的全球范围内的污染。不过,我并不想用RequireJS在我AngularJS应用现在,因为我认为AngularJS是我的使用不够好,这增加了复杂性。
One possible solution I can think of is using TypeScript's import and export somehow, which in turn will use RequireJS. This probably will wrap the HelloService within a define function, thus avoiding pollution of the global scope with HelloService. However, I don't want to use RequireJS in my AngularJS application for now, as I think AngularJS is good enough for my use, and it adds complexity.
所以,我的问题是,我怎么可以定义使用打字稿类的AngularJS服务,不污染在全球范围内?
So, my question is, how can I define an AngularJS service using a TypeScript class that doesn't pollute the global scope?
推荐答案
我应该提供什么我实际上做结束:
I should provide what I actually ended doing:
module MyModule {
export class HelloService {
public getWelcomeMessage():String {
return "Hello";
}
}
angular.module('app.services.helloService', []).factory('helloService', () => {
return new HelloService();
});
}
在这种方式我可以使用
return new HelloService();
而不是
return new MyModule.HelloService();
这篇关于我如何定义使用打字稿类,不污染在全球范围内的AngularJS服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!