2

I write services and controllers in my app (Angularjs - 1.6.3) using es6 classes.

I want to simplify some piece of code but don't know whether it's possible and how to get es6 class constructor arguments list.

Example of piece i need to simplify to prevent duplication:

class MyService {

    constructor (
        $q,
        $translate,
    ) {

        this.$q = $q;
        this.$translate = $translate;
    }
}

angular
    .module('app')
    .service('myService', MyService);

Is there any way to add dependencies to given context automatically?

Know that in angular2 there are decorators which helps not to duplicate dependencies to add them in current scope (or they do this any other way)

Rantiev
  • 2,121
  • 2
  • 32
  • 56

1 Answers1

0

You could use Object.assign combined with destructuring:

class Service {
    constructor($q, $translate) {
        Object.assign(this, { $q, $translate });
    }
}

This is equivalent to the code you wrote.

Husky
  • 5,757
  • 2
  • 46
  • 41
  • If this is the answer, isn't the question a duplicate of [this](https://stackoverflow.com/questions/27529518/automatically-set-arguments-as-instance-properties-in-es6)? I'm not sure what the OP meant by "get arguments list". – Bergi Jan 31 '18 at 18:34
  • The question is indeed the same thing, formulated using other words. – Rantiev May 31 '18 at 14:15
  • @Husky it's the way i have it now, tx. – Rantiev May 31 '18 at 14:16