AngularJS - Use ES6 imports instead of angular DI system

后端 未结 1 1618

I\'m using Webpack with angular 1.6.x and Typescript and I quit using angular DI in favor of ES6 imports. When I need some ng functions like $http, $resou

相关标签:
1条回答
  • 2020-12-21 19:32

    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.

    0 讨论(0)
提交回复
热议问题