【发布时间】:2015-10-01 16:36:26
【问题描述】:
首先介绍一下我想要实现的目标。我有一项服务需要在注入和使用之前进行一些配置。在做了一些研究之后,我认为拥有该服务的提供商将是最好的解决方案。所以我根据this example实现了provider。即使 Typescript 编译器(我正在使用 typescript 将我的代码编译成有效的 JavaScript)认为没问题,JavaScript 也无法识别可通过提供程序设置某些选项的函数。
我的代码如下(某些代码因某种原因被遗漏或重命名)
export interface ICustomServiceProvider extends ng.IServiceProvider {
setOptions(options: ICustomOptions): void;
$get($http, $window, $resource): ICustomService;
}
class CustomServiceProvider implements ICustomServiceProvider {
private options: ICustomOptions;
public $get($http, $window, $resource) {
return new CustomService($http, $window, $resource);
}
public setOptions(options: ICustomOptions): void {
this.options = options;
}
}
angular.module('custom', ['ngResource'])
.service('CustomService', CustomService)
.provider('CustomService', CustomServiceProvider);
在我的一个单元测试中使用提供程序(我使用 Karma 和 Mocka 进行测试)并调用 setOptions 函数时会出现问题。就是这样完成的。
describe('CustomService', function() {
var provider: ICustomServiceProvider;
var options: {hello: 'world'};
beforeEach(inject(function($injector: ng.auto.IInjectorService) {
provider = <ICustomServiceProvider> $injector.get('');
}));
it('CustomService provider test', function() {
provider.setOptions(options);
});
}
运行此测试时,Karma 会抛出错误提示
TypeError: provider.setOptions is not a function at Context.[anonymous]
此外,编译后的 JavaScript Visual Studio 代码在 .provider('CustomService', CustomServiceProvider); 行的提供程序变量上给了我一个绿色警告(我认为这不是错误)
“() => void”类型的参数不能分配给“IServiceProvider”类型的参数。类型“() => void”中缺少属性“$get”。
(本地变量) CustomServiceProvider: () => void
提供者
我已经花了几个小时来解决这个问题,但似乎找不到解决方案。关于如何解决我做错的任何想法?
提前致谢。
编辑 (30-09-2015)
我说的服务是这样的:
export interface ICustomService {
// Some function definitions
}
class CustomService implements ICustomService {
static $inject = ['$http', '$window', '$resource'];
constructor(httpService: ng.IHttpService, windowService: ng.IWindowService, resourceService: ng.resource.IResourceService, options: ICustomOptions) {
// Setting variables
}
}
【问题讨论】:
标签: javascript angularjs typescript karma-mocha angular-providers