ES modules cannot replace Angular modules and DI. They compliment each other and keep the application modular and testable.
ES6 modules provide extra layer of extensibility, for example controller/service subclassing (something that doesn't look good with Angular modules and DI alone).
The recommended approach with ES6 or TypeScript is to do DI conventionally, with $inject
annotation:
export class PostsService {
static $inject = ['$http'];
constructor(
public $http: angular.IHttpService
) {}
...
}
It's also a good practice to have one module per file, this way the application stays modular and testable:
export default angular.module('app.posts', [])
.service('posts', `PostsService)
.name;`
Its default
export is module name that can be imported in another module that directly depends on it:
import postsModule from '...';
...
export default angular.module('app.controller', [postsModule])
.controller('controller', Controller)
.name;`
Application injector cannot be normally reached from a decorator. Even if it's possible with a hack to make it work in production, it will be messed up in tests.
angular.injector
creates new injector (i.e. application instance) and has very limited proper uses in production:
angular.injector(['ng']).get('$rootScope') !== angular.injector(['ng']).get('$rootScope');
It is often misused when a developer doesn't know how to get current $injector
instance. It certainly shouldn't be used in a case like this one.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…