【发布时间】:2018-01-15 18:56:18
【问题描述】:
结合使用 Angular 1.6 和 ES6 类我遇到了以下问题:
我写了一个有一些依赖的服务(惊喜!)
class myService {
/*@ngInject*/
constructor($q){
this.$q = $q;
this.creationDate = new Date();
}
doStuff(data){
return this.$q.when(data);
}
}
angular.module('app').service('myService', myService)
但是我得到了一个构建目标,其中的服务需要更高级一些,所以我对其进行了扩展并在这种情况下使用了扩展服务:
class myFancyService extends myService{
/*@ngInject*/
constructor($q, $http){
super($q);
this.$http = $http;
}
doFancyStuff(data){
console.log(this.creationDate);
return this.doStuff(data)
.then((stuff) => this.$http.post('api.myapp', stuff));
}
}
angular.module('app').service('myService', myFancyService)
到目前为止,这工作正常,但有一个主要缺点:
通过调用super(dependencies),我的基类的依赖项无法从@ngInject 自动注入。因此,我需要非常清楚,每当我更改 myService 的依赖项时,myFancyService(以及任何其他潜在的未来子类)的依赖项也需要更改。
我不能使用组合代替继承,因为myService 没有注册为角度服务,因此不能作为依赖注入。
问题:
有没有办法自动注入基类的依赖项?
如果没有,至少有办法让我的单元测试提醒我需要更新myFancyService 的依赖项吗?如果super($q) 的参数(或者可能只是参数的数量)等于 myService-constructor 的参数(数量),我还没有找到一种方法来测试 karma/jasmine。
【问题讨论】:
标签: angularjs class inheritance dependency-injection ecmascript-6