问题描述
限时送ChatGPT账号..我正在使用 AngularJS 和 TypeScript.我想使用 Typescript 类实现 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 代码:
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.").
我能想到的一种可能的解决方案是以某种方式使用 TypeScript 的导入和导出,而后者又将使用 RequireJS.这可能会将 HelloService 包装在一个定义函数中,从而避免 HelloService 对全局范围的污染.但是,我现在不想在我的 AngularJS 应用程序中使用 RequireJS,因为我认为 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.
那么,我的问题是,如何使用不会污染全局范围的 TypeScript 类来定义 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();
这篇关于如何使用不会污染全局范围的 TypeScript 类定义 AngularJS 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论