gpt4 book ai didi

AngularJS:需要复制继承的依赖项?

转载 作者:行者123 更新时间:2023-12-01 12:19:36 24 4
gpt4 key购买 nike

结合使用 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 自动注入(inject)。因此,我需要非常清楚,每当我更改 myService 的依赖项时,myFancyService 的依赖项(以及任何其他潜在的 future 子类)也需要更改.

我不能使用组合而不是继承,因为 myService 没有注册为 angular.service ,因此不能作为依赖注入(inject)。

问题:

有没有办法自动注入(inject)基类的依赖?

如果没有,是否至少有一种方法可以让我的单元测试提醒我需要更新 myFancyService 的依赖项?如果 super($q) 的参数(或者可能只是参数数量)等于 myService 的参数(数量),我还找不到用 karma/jasmine 进行测试的方法- 构造函数

最佳答案

要记住两点:

  1. 继承中具有接口(interface)一致性的模式是必不可少的,子类可以重新实现方法或属性,但它们不能改变方法的调用方式(参数等。 .)
  2. 仍在将BaseService注册到依赖注入(inject),但您可能不需要这样做,因为它看起来像一个抽象类为你。

这可以解决您的问题(运行脚本以查看发生了什么)您基本上需要在每个 derived class 中扩展 static $inject 属性,并在每个子构造函数中使用解构:

  • 好处:您不需要知道父类有哪些依赖项。
  • 约束:始终在子类中使用第一个参数(因为rest operator 必须是最后一个)

function logger(LogService) {
LogService.log('Hello World');
}

class BaseService {
static get $inject() {
return ['$q'];
}

constructor($q) {
this.$q = $q;
}

log() {
console.log('BaseService.$q: ', typeof this.$q, this.$q.name);
}
}

class ExtendedService extends BaseService {
static get $inject() {
return ['$http'].concat(BaseService.$inject);
}

constructor($http, ...rest) {
super(...rest);
this.$http = $http;
}

log() {
super.log();
console.log('ExtendedService.$http: ', typeof this.$http, this.$http.name);
}
}


class LogService extends ExtendedService {
static get $inject() {
return ['$log', '$timeout'].concat(ExtendedService.$inject);
}

constructor($log, $timeout, ...rest) {
super(...rest);
this.$log = $log;
this.$timeout = $timeout;
}

log(what) {
super.log();
this.$timeout(() => {
this.$log.log('LogService.log', what);
}, 1000);
}
}

angular
.module('test', [])
.service('BaseService', BaseService)
.service('ExtendedService', ExtendedService)
.service('LogService', LogService)
.run(logger)
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>

<section ng-app="test"></section>


我还在 babel-plugin-angularjs-annotate 中打开了一个功能请求: https://github.com/schmod/babel-plugin-angularjs-annotate/issues/28

关于AngularJS:需要复制继承的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com