简体   繁体   中英

How to inject modules properly in AngularJS

Lets assume I have js/modules/auth js/modules/home js/modules/panel directories. My main app.js looks like this:

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

Then I inject them like this:

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

I have in js/modules/auth/services/authService.js two factories:

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

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

Basically I am trying to implement https://github.com/fnakstad/angular-client-side-auth But when I in app.js have line:

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

I get: Uncaught Error: [$injector:unpr] Unknown provider: myApp.auth.services.AuthProvider

So can anyone give me a hint how to properly inject modules - services etc.. ?

You can't have two modules initialized with the same name. You should either name it differently or just call it the second time: angular.module('some_name',[]) will initialize a new module where as angular.module('some_name') will call an existing module.

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

   angular.module('myApp.auth.services')
   .factory('Users', function($http)

Each module should inject dependent libraries/modules

//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'])

Henceforth, to use the module you don't need to inject dependencies, so

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

angular.module('myApp.auth.services')
.factory('Users', function($http)

Once a module is defined, it has to used directly instead of defining it every time it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM