一位同事声称这是向Angular注入纯ES6 JavaScript类的错误方法.我很好奇是否有更好的方法(更正确)?
顺便说一句,将注入的依赖项(在此示例中为$timeout)附加到实例是否更好(以及为什么更好);例如,构造函数中的._ $timeout = $timeout.我个人认为在这种情况下做这件事没有任何好处.
class.factory.js
let ClassFactory = function($timeout) {
// Factory function that simply returns class constructor.
class MyClass {
constructor(a,b) {
// contrived class
this.a = a;
this.b = b;
this.c = null;
}
applyChange() {
// contrived class method
const SELF = this;
$timeout(() => {
SELF.c = SELF.a + SELF.b;
});
}
}
return MyClass ;
};
ClassFactory.$inject = ['$timeout'];
export default ClassFactory;
app.module.js
import ClassFactory from './factories/class.factory';
import AppService from './services/app.service';
export default angular.module('myApp',[])
.factory('ClassFactory',ClassFactory)
.service('AppService',AppService);
稍后,在其他地方我们可以在某些服务或控制器中使用该类来构造新的MyClass实例.
app.service.js
class AppService {
// contrived usage of our dependency injected pure class.
constructor(ClassFactory) {
this.array = [];
this._ClassFactory = ClassFactory;
}
initialize(a,b) {
// We can instantiate as many "MyClass" objects as we need.
let myClass = new this._ClassFactory(a,b);
this.array.push(myClass);
}
static serviceFactory(...injected) {
AppService.instance = new AppService(...injected);
return AppService.instance;
}
}
AppService.serviceFactory.$inject = ['ClassFactory'];
export default AppService.serviceFactory;
最佳答案
在这一点上,$timeout是类属性还是只是局部变量并不重要.
包含具有工厂功能的类在ES6开发中不能很好地进行,因此无法导出和扩展它.需要工厂的事实可能表明设计问题.
像这样的类可以通过依赖注入来获取依赖关系(在common sense中).当类构造函数也应该使用非依赖性参数调用时,这是常见的事情:
export class MyClass {
constructor($timeout,a,b) {
this._$timeout = $timeout;
...
}
}
...
obj = new MyClass($timeout,b);
如果有多个依赖项,则可以提供$injector依赖项而不是所有依赖项:
export class MyClass {
constructor($injector,b) {
this._$timeout = $injector.get('$timeout');
...
}
}
...
obj = new MyClass($injector,b);
可能还存在导致依赖于$timeout的设计问题,并且通过解决它可以避免依赖性.从上面的代码中不清楚为什么MyClass应该用$timeout触发摘要,它的逻辑不包含任何需要它的东西.使用MyClass实例并将其绑定到视图或任何摘要的代码是代码的责任.