A colleague claims this is the wrong way to introduce a clean ES6 JavaScript class in Angular. I am curious if there is a better way (or rather)?
As an aside, is it better (and why better) to attach a nested dependency example ( $timeoutin this example); for example, this._$timeout = $timeoutin the constructor. I personally believe that in this case there is no advantage for this.
class.factory.js
let ClassFactory = function($timeout) {
class MyClass {
constructor(a, b) {
this.a = a;
this.b = b;
this.c = null;
}
applyChange() {
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);
Later, in another place, we can use the class in some service or controller to create new instances of 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;
James source
share