如何从不同模块使用两个具有相同名称的AngularJS服务? [英] How to use two AngularJS services with same name from different modules?

查看:229
本文介绍了如何从不同模块使用两个具有相同名称的AngularJS服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个用于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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆