The correct way to introduce a pure class in an angular 1.x application in ES6

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) {
    // 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);

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;
+4
source share
1 answer

, $timeout .

factory ES6, . , a factory , , .

( ). , , :

export class MyClass {
  constructor($timeout, a, b) {
    this._$timeout = $timeout;
    ...
  }
}
...
obj = new MyClass($timeout, a, b);

, ​​ $injector :

export class MyClass {
  constructor($injector, a, b) {
    this._$timeout = $injector.get('$timeout');
    ...
  }
}
...
obj = new MyClass($injector, a, b);

, $timeout, , , . , MyClass $timeout, , . , MyClass - , .

+3

Source: https://habr.com/ru/post/1679156/


All Articles