我正在使用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服务?
为什么我在以下代码中遇到编译错误(请参阅注释行)?
public void Test()
{
HashSet<HashSet<Animal>> setWithSets = new HashSet<HashSet<Animal>>();
HashSet<Cat> cats = new HashSet<Cat>();
setWithSets.Add(cats); // Compile error
}
private class Animal { }
private class Cat : Animal { }
Run Code Online (Sandbox Code Playgroud)
VS2012给了我两个错误,第一个错误:
我的问题是:为什么我不能在"setWithSets"中添加"cats"?
我试图窥探$ timeout,以便我可以验证它没有被调用.具体来说,我的生产代码(见下文)将$ timeout称为函数,而不是对象:
$timeout(function() { ... })
Run Code Online (Sandbox Code Playgroud)
并不是
$timeout.cancel() // for instance
Run Code Online (Sandbox Code Playgroud)
然而,Jasmine需要一个物体被监视,如下所示:
spyOn(someObject, '$timeout')
Run Code Online (Sandbox Code Playgroud)
我不知道'someObject'会是什么.
我正在使用Angular模拟,如果这有任何区别.
编辑:我正在尝试测试的相关生产代码如下所示:
EventHandler.prototype._updateDurationInOneSecondOn = function (call) {
var _this = this;
var _updateDurationPromise = this._$timeout(function () {
call.duration = new Date().getTime() - call.startTime;
_this._updateDurationInOneSecondOn(call);
}, 1000);
// ... more irrelevant code
}
Run Code Online (Sandbox Code Playgroud)
在特定的测试场景中,我试图断言永远不会调用$ timeout.
编辑2:明确指出我使用$ timeout作为函数,而不是对象.
angularjs ×2
c# ×1
collections ×1
generics ×1
hashset ×1
jasmine ×1
spy ×1
typescript ×1
unit-testing ×1