如何在AngularJS中正确注入模块

How to inject modules properly in AngularJS

本文关键字:注入 模块 AngularJS      更新时间:2023-09-26

假设我有js/modules/auth-js/modules/home-js/modules''panel目录。我的主应用程序.js看起来是这样的:

angular.module('myApp.homeApp', ['myApp.homeApp.services']);
angular.module('myApp.auth', ['myApp.auth.services']);
angular.module('myApp.panelApp', []);

然后我像这样注入它们:

var myApp = angular.module('myApp', ['ngCookies', 'ui.router', 'ui.bootstrap', 'angular.css.injector', 'myApp.auth', 'myApp.homeApp', 'myApp.panelApp'])

我在js/modules/auth/services/authService.js中有两个工厂:

angular.module('myApp.auth.services', [])
.factory('Auth', function($http, $cookieStore)
angular.module('myApp.auth.services', [])
.factory('Users', function($http)

基本上我正在努力实现https://github.com/fnakstad/angular-client-side-auth但当我在app.js中有行时:

myApp.run(['$rootScope', '$state', 'myApp.auth.services.Auth', function ($rootScope, $state, Auth)

我得到:未捕获错误:[$injector:unp]未知提供程序:myApp.auth.services.AuthProvider

所以,有人能给我一个提示,如何正确地注入模块-服务等?

不能用相同的名称初始化两个模块。您应该以不同的方式命名它,或者只调用第二次:angular.module('some_name',[])将初始化一个新模块,而angular.module('some_name')将调用一个现有模块。

   angular.module('myApp.auth.services', [])
   .factory('Auth', function($http, $cookieStore)
   angular.module('myApp.auth.services')
   .factory('Users', function($http)

每个模块都应该注入依赖的库/模块

//module injection indicates Module definition. When you see `[]` is used, 
//a module is defined
angular.module('myApp.homeApp', ['ngRoute', 'ngResource']); //for example
angular.module('myApp.auth', []);
angular.module('myApp.panelApp', []);
var myApp = angular.module('myApp', ['ngCookies', 'ui.router', 'ui.bootstrap',
                                     'angular.css.injector', 'myApp.auth',  
                                     'myApp.homeApp', 'myApp.panelApp'])

从此以后,要使用该模块,您不需要注入依赖项,因此

angular.module('myApp.auth.services', [])
.factory('Auth', function($http, $cookieStore)
angular.module('myApp.auth.services')
.factory('Users', function($http)

一旦定义了模块,就必须直接使用它,而不是每次使用时都定义它。