ng-di
ng-di copied to clipboard
Add class support for service constructors
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)))();
}