如何使用来自不同模块的两个同名 AngularJS 服务? [英] How to use two AngularJS services with same name from different modules?
问题描述
假设我有两个用于 AngularJS 的模块,例如foo
和 bar
,它们都定义了一个名为 baz
的服务.
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' ]);
然后我可以尝试使用baz
服务在控制器中使用
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?
推荐答案
服务定位器按名称查找服务 (angularjs 指南 DI).但是 Namespacing"AngularJS 中的服务:
The service locator looks services up by name (angularjs guide DI). However "Namespacing" services in AngularJS:
截至今天,AngularJS 不处理服务的命名空间冲突所以如果你有 2 个不同的模块,服务名称相同方式并且您在应用程序中包含两个模块,则只会有一项服务可用.
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.
我猜你可以手工"创建完全限定的名称:将服务命名为 foo.baz
和 bar.baz
而不是普通的 baz
代码>.这是一种自我欺骗.此外,以这种方式编写它并不能使命名空间成为现实,但阅读代码的其他人可能会这么认为.
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.
这篇关于如何使用来自不同模块的两个同名 AngularJS 服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!