How to use two AngularJS services with same name from different modules?

后端 未结 2 890
半阙折子戏
半阙折子戏 2021-02-02 09:02

Supposed I have two modules for AngularJS, e.g. foo and bar, and both of them define a service called baz.

In my application I dep

相关标签:
2条回答
  • 2021-02-02 09:33

    When we have two services with the same name, you have to differentiate them while using it in your local module. Let's see some code below to understand how it works,

    I have two Util services and need to differentiate them,

    angular
      .module('module1', [
      ])
      .service('UtilService', UtilService)
      .service('another.UtilService', UtilService)
      .name;
    

    In the controller file, you can simply inject like below.

    export class Controller {
      public static $inject: string[] = ['UtilService', 'another.UtilService'];
    
    constructor(
        private utilService: UtilService,
        private anotherUtilService
      ) {
         console.log(this.utilService) // will print the main util service methods
         console.log(this.anotherUtilService) // will print the another util service 
         methods
      }
    
    0 讨论(0)
  • 2021-02-02 09:43

    The service locator looks services up by name (angularjs guide DI). However "Namespacing" services in AngularJS:

    As of today AngularJS doesn't handle namespace collisions for services so if you've got 2 different modules with the service named the same way and you include both modules in your app, only one service will be available.

    I guess you can make the fully qualified name "by hand": name the service foo.baz and bar.baz instead of plain baz. It's kind of a self-delusion. Moreover, writing it this way doesn't make namespacing real, but another person that reads the code might think so.

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