我正在使用AngularJS和TypeScript.我想使用Typescript类实现AngularJS服务,如下所示:
class HelloService {
public getWelcomeMessage():String {
return "Hello";
}
}
angular.module('app.services.helloService', []).factory('helloService', () => {
return new HelloService();
});
Run Code Online (Sandbox Code Playgroud)
这将编译为以下javascript代码:
var HelloService = (function () {
function HelloService() {
}
HelloService.prototype.getWelcomeMessage = function () {
return "Hello";
};
return HelloService;
})();
angular.module('app.services.helloService', []).factory('helloService', function () {
return new HelloService();
});
Run Code Online (Sandbox Code Playgroud)
这会使用变量HelloService污染全局命名空间,这显然是我不想要的.(使用Chrome的控制台我验证了HelloService是一个对象.)如何解决/避免此问题?
我试过了明显的事:
angular.module('app.services.helloService', []).factory('helloService', function () {
class HelloService { ...}
return new HelloService();
});
Run Code Online (Sandbox Code Playgroud)
但这给了我一个编译错误("意外的令牌;预期的'声明'.").
我能想到的一个可能的解决方案是以某种方式使用TypeScript的导入和导出,而这又将使用RequireJS.这可能会将HelloService包装在define函数中,从而避免使用HelloService污染全局范围.但是,我现在不想在我的AngularJS应用程序中使用RequireJS,因为我认为AngularJS足够好用于我的使用,并且它增加了复杂性.
所以,我的问题是,如何使用不污染全局范围的TypeScript类来定义AngularJS服务?