ng-di icon indicating copy to clipboard operation
ng-di copied to clipboard

Add class support for service constructors

Open platdesign opened this issue 8 years ago • 0 comments

First of all: Nice work!

It would be nice to be able to use classes as service constructors.

class UserService {
  constructor($db) {
    this.$db = $db;
  }
}
UserService.$inject = ['$db'];

mod.factory('$db', ...);
mod.service('User', UserService);

The problem is the instantiate function. Class constructors always need to be invoked with 'new'. Maybe sth like this could do the job:

function getArgs(fn, self, locals) {
  var args = [],
    $inject = annotate(fn),
    length, i,
    key;

  for (i = 0, length = $inject.length; i < length; i++) {
    key = $inject[i];
    args.push(
      locals && locals.hasOwnProperty(key) ?
        locals[key] :
        getService(key)
    );
  }

  return args;
}


function instantiate(Type, locals) {
  var args = getArgs(Type, null, locals);
  return new (Type.bind.apply(Type, [null].concat(args)))();
}

platdesign avatar Jul 16 '16 22:07 platdesign