gpt4 book ai didi

angularjs - 在 Angular 中,是否有理由不在模块声明中列出模块依赖项?

转载 作者:行者123 更新时间:2023-12-03 00:17:45 25 4
gpt4 key购买 nike

在我读过的有关 Angularjs 的所有教程和示例中,它们都定义了带有空列表作为第二个参数的模块:

angular.module('myModule', []);

我知道创建新模块需要第二个参数的存在,但我不明白为什么列表中从来没有任何元素。 angular.module 的文档没有说明列表的内容将代表什么。

但是,通过定义我的应用程序模块,我了解到该列表代表新模块所依赖的模块 - 那么为什么应用程序子模块它总是为空?例如,在我自己的项目中,我有一个我的应用程序所依赖的用户模块:

/* app.js */
angular.module('myApp', [
'ngCookies',
'ngResource',
'ui.bootstrap',
'ui.router',
'myApp.system',
'myApp.users'
]);

angular.module('myApp.system', []);
angular.module('myApp.users', []);

当我终于开始学习如何使用 karma 和 jasmine 进行单元测试时,我花了几个小时试图找出此错误消息:

Error: [$injector:modulerr] Failed to instantiate module myApp.users due to:
Error: [$injector:unpr] Unknown provider: $stateProvider
http://errors.angularjs.org/1.2.13/$injector/unpr?p0=%24stateProvider
at /Users/matt/Development/myApp/public/lib/angular/angular.js:3556
at getService (/Users/matt/Development/myApp/public/lib/angular/angular.js:3683)
at invoke (/Users/matt/Development/myApp/public/lib/angular/angular.js:3710)
at /Users/matt/myApp/public/lib/angular/angular.js:3639

最终我发现有两件事可以解决这个问题 - 要么我可以在测试代码中加载模块依赖项,要么我可以将依赖项添加到用户模块声明中的空列表中:

/* UserControllerTest.js */
describe('UserCtrl', function () {

var $rootScope,
$scope,
controller;

beforeEach(function () {
module('ui.router');
module('myApp.system');
module('ngResource');
module('myApp.users');

inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
controller = $injector.get('$controller')('UserCtrl', {$scope: $scope});
});
});

it('should work', function () {
expect(true).toBe(true);
});

});

或者:

/* app.js */
...
angular.module('myApp.users', [
'ngResource',
'ui.router',
'mean.system'
]);

有什么原因我不想做后者吗?为什么我在文档和教程中从未看到过这一点 - 它会阻止我在测试中模拟这些依赖项吗?

为什么我不需要后一个子模块定义来正常运行我的应用程序?我确实为 UserCtrl 指定了一系列“注入(inject)局部变量” - 为什么这对于单元测试来说还不够?

最佳答案

模块的目的是封装代码的自包含部分(例如可重用的小部件、实现特定功能的代码 tgst 等)。一般来说,让每个模块声明它所依赖的依赖项是一个很好的做法。

如果不是,那么该模块依赖于需要它声明这些依赖项的模块,这会扰乱“ self 包含”,损害可测试性和可重用性,并引入一堆潜在的 future 错误。

也就是说,似乎没有理由不声明每个模块的依赖关系。 (不,它不会阻止您在单元测试中模拟依赖项。)当然,正如人们所期望的那样,即使多个模块需要每个模块,也会加载一次。

API引用确实对angular.module不是很详细,但是 Developer Guide 有更广泛的描述。

例如,引用“依赖项”部分:

Modules can list other modules as their dependencies. Depending on a module implies that required module needs to be loaded before the requiring module is loaded. In other words the configuration blocks of the required modules execute before the configuration blocks of the requiring module. The same is true for the run blocks. Each module can only be loaded once, even if multiple other modules require it.

关于angularjs - 在 Angular 中,是否有理由不在模块声明中列出模块依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23848850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com