Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js DI with (ES6) classes and inheritance

Background, current implementation of classes/modules in our app is common.js and CoffeeScript classes. I'm desperately looking for a solution to work with ES6 or TypeScript, but the problem remains.

How to do DI with class inheritance using Angular-1.x?

Given the code:

// SuperService.js
class SuperService {
  constructor($http, $q, $etc) {
    // Implementation is not important ...  
  }   
}
export { SubService }

// SubService.js
import { SuperService } from './SuperService';
class SubService extends SuperService {
  constructor($more, $di, $things, $here) {
    // Implementation is not important ... 
    // // // // // // // // // // 
    // Problem exists here ... //
    // // // // // // // // // //
    super($we, $need, $all, $the, $super, \
          $class, $di, $things, $every, $time, $we, \
          $inherit, $from, $it)
  }
}
export { SubService }

Must one, in the SubService here redefine all the parent DI requirements in order to successfully call super()?

We're presently doing something akin to the following:

// CoffeeScript                              // Javascript
app.factory "subService", (Service) ->       app.factory("subService", function(Service) {
  SubService = () ->                           var SubService;
    Service.call(@)                            SubService = function() {
    @                                            Service.call(this);
                                                 return this;
  # Overwrite some stuff on the "Service"      };
  Service::basepath = "/environments"          Service.prototype.basepath = "/environments";
  Service::model = Environment                 Service.prototype.model = Environment;
                                               return new SubService();
  new SubService()                           });

Which is also less than ideal, aside from being ugly.

like image 265
Lee Hambley Avatar asked Mar 12 '15 14:03

Lee Hambley


1 Answers

it's not ES6 (it's ES7), but it just might float your boat

I would look into angular-decorators by MikeRyan52.

He's put together an @inject decorator that works as follows:

@inject('$http', '$rootScope')
class SomeClass {
  constructor($http, $rootScope) {

  }
}

@inject('$q')
class SubClass extends SomeClass {
  constructor($q, ...parentDependencies) { /** parent dependencies caught with a rest parameter **/
    super(...parentDependencies);
  }
}

the implementation of @inject

like image 154
Kasper Lewau Avatar answered Oct 11 '22 17:10

Kasper Lewau