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

2

28

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 depend on them by saying:

var app = angular.module('app', [ 'foo', 'bar' ]);

Then I can try to use the baz service in a controller by using

app.controller('blaController', [ '$scope', 'baz', function($scope, baz) {
  // ...
}]);

How can I define which of the two services I'd like to use? Is there something such as a fully-qualified name?

Brambling answered 25/7, 2013 at 15:23 Comment(3)
possible duplicate of How to reference values with the same name from different modulesAnaphase
possible duplicate of "Namespacing" services in AngularJSRisarise
possible duplicate of Modules and name clashes in AngularjsAnacoluthia
S
39

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.

Storeroom answered 25/7, 2013 at 16:36 Comment(1)
I forgot to mention that you can mitigate this with closures (function() { module declaration}());Storeroom
Q
0

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
  }
Quinquereme answered 4/6, 2019 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.