與ES6類我跑進了以下問題結合採用了棱角分明1.6:(!驚喜)AngularJS:繼承的依賴關係需要重複嗎?
我寫了一個服務,一些依賴
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
未註冊爲角度服務,因此無法注入爲依賴關係。
問:
是否有辦法來自動反正注入基類的依賴呢?
如果沒有,是否至少有一種方法讓我的unittests提醒我,我需要更新myFancyService
的依賴關係?如果super($q)
的參數(或者可能只是參數的個數)等於myService- constructor
的(數量)參數,我還找不到一種方法來使用karma/jasmine進行測試。
因爲['properties initializers'](https:// esdiscuss。),所以我使用了'static getter'。org/topic/es7-property-initializers)不是標準的(如果你使用babel或打字稿,你也可以使用它們)。 – Hitmands
這太好了,非常感謝!我正在更多地閱讀'ng-annotate'和'$ inject'-property,看看我能不能自動注入服務而不是輸入字符串數組(並保持它與參數列表同步) )。但除此之外,這正是我一直在尋找的! –
如果它完成了這項工作,那麼請在調查後接受它。 – Hitmands