76

在下面的示例测试中,原始提供程序名称是 APIEndpointProvider,但对于注入和服务实例化,约定似乎是它必须用下划线包裹它来注入。这是为什么?

'use strict';

describe('Provider: APIEndpointProvider', function () {

  beforeEach(module('myApp.providers'));

  var APIEndpointProvider;
  beforeEach(inject(function(_APIEndpointProvider_) {
    APIEndpointProvider = _APIEndpointProvider_;
  }));

  it('should do something', function () {
    expect(!!APIEndpointProvider).toBe(true);
  });

});

我缺少更好的解释的约定是什么?

4

1 回答 1

109

下划线是一种方便的技巧,我们可以使用它来以不同的名称注入服务,以便我们可以在本地分配与服务同名的局部变量。

也就是说,如果我们不能这样做,我们将不得不在本地为服务使用其他名称:

beforeEach(inject(function(APIEndpointProvider) {
  AEP = APIEndpointProvider; // <-- we can't use the same name!
}));

it('should do something', function () {
  expect(!!AEP).toBe(true);  // <-- this is more confusing
});

测试中$injector使用的 能够只删除下划线以提供我们想要的模块。除了让我们重用相同的名称之外,它什么也不做。

在 Angular 文档中阅读更多内容

于 2013-03-10T02:06:15.683 回答