简体   繁体   中英

AngularAMD: the app depends on services but services depend on the app

I am clearly missing something very basic.

The instructions are to create an app, like this:

define(['angularAMD'], function (angularAMD) {
    var app = angular.module(app_name, ['webapp']);
    ... // Setup app here. E.g.: run .config with $routeProvider
    return angularAMD.bootstrap(app);
});

And then create subsequent items like this:

define(['app'], function (app) {
    app.factory('Pictures', function (...) {
        ...
    });
});

And there is this helpful line:

Any subsequent module definitions would simply need to require app to create the desired AngularJS services

Well that's just great for subsequent module definitions, but app.config and app.run need lots of prerequisite modules that I am supposed to create -- as would any application beyond the level of a toy. So there is obviously some simple solution that I am missing. How do I create services that the app depends on?

You can simply use 'angularAMD' injection to create services. For example,

define(['angularAMD'], function (angularAMD) {
  angularAMD.service('LoggerService',['$log',function($log){
     return function(msg){
        $log.log('message:', msg);
     }
  }]);

});

The services created using this method are available before the application is bootstrapped. Hence app can depend on these services.

More similar code can be found at angular-AMD sample app.

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