最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Access Angular service when manually bootstrappinginitializing - Stack Overflow

programmeradmin0浏览0评论

Is it possible to access to a method of a factory service, before Angular has been bootstrapped, similar to the code below?

I need to make a number of AJAX requests before Angular starts in order to set a number of global application variables. I had hoped to keep the logic for this and/or store the responses inside an Angular service, and return a promise...

<script src="scripts/app.js"></script>
<script src="scripts/factories/app.js"></script>

<script>
    angular.element(document).ready(function() {

        factoryName.startup().then(function() {
            angular.bootstrap(document, ['MyApp']);
        }, function(err) {
            console.log(error fetching bootstrap data);
        }

    });
</script>

Is there an alternative method to use to get a similar behaviour?

Is it possible to access to a method of a factory service, before Angular has been bootstrapped, similar to the code below?

I need to make a number of AJAX requests before Angular starts in order to set a number of global application variables. I had hoped to keep the logic for this and/or store the responses inside an Angular service, and return a promise...

<script src="scripts/app.js"></script>
<script src="scripts/factories/app.js"></script>

<script>
    angular.element(document).ready(function() {

        factoryName.startup().then(function() {
            angular.bootstrap(document, ['MyApp']);
        }, function(err) {
            console.log(error fetching bootstrap data);
        }

    });
</script>

Is there an alternative method to use to get a similar behaviour?

Share Improve this question asked Nov 11, 2013 at 14:41 umpljazzumpljazz 1,2224 gold badges12 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You can make the first service calls in module run blocks. When a later service call is made for those variables, you can either serve them out of $http's cache or have explicitly cached the promise from the first call.

// example
myApp.run(function(MyService) {
  // call your function when Angular starts up
  MyService.init();
});

Below is an example that loads a configuration file before bootstrapping the application.

The first call to bootstrap is done to gain access to angular services like $http and $location (you could also inject your own module at this point to access custom services).

After the configuration file has been loaded, angular.bootstrap is called for the main application, with the loaded configuration set as a constant on a makeshift module(rsacAppBootstrap) that is injected.

Here are at least two advantages over using a promise set from a run block:

  1. Reduced boilerplate of promise for everything dependent on configuration
  2. Ability to conditionally load dependencies based on the environment using RequireJS

Custom bootstrap script:

angular.bootstrap().invoke(function ($http, $location) {

  var env = $location.search()._env || null;
  if (env === true) {
    env = null;
  }

  var configUri = 'config/env.json';
  if (env) {
    configUri = configUri.replace('json', env + '.json');
  }

  var rsacAppBootstrap = angular.module('rsacAppBootstrap', [])
    .run(function ($rootScope, $location, $window) {
      var env = $location.search()._env;
      $rootScope.$on('$locationChangeSuccess', function () {
        var newEnv = $location.search()._env;
        if (env !== newEnv) {
          $window.location.reload();
        }
      })
    });

  function bootstrap(config) {
    rsacAppBootstrap.constant('rsacConfig', config || {});
    angular.element(document).ready(function () {
      var modules = ['rsacApp', 'rsacAppBootstrap'];
      if (config.modules){
        config.modules.forEach(function(v){
          modules.push(v);
        })
      }
      angular.bootstrap(document, modules);
    });
  }

  $http.get(configUri)
    .success(function (config) {
      config._env = env;
      if (config.require) {
        require(config.require, function(){
          bootstrap(config);
        });
      } else {
        bootstrap(config);
      }
    })
    .error(function () {
      bootstrap();
    });

});

Example configuration file:

{
  "_meta": [
    "Development environment settings"
  ],

  "require":[
    "//code.angularjs/1.2.3/angular-mocks.js",
    "ponents/rsacMock/js/rsacMock.js"
  ],

  "modules":[
    "ngMockE2E",
    "rsacMock"
  ],

  "resources": { ... }

}
发布评论

评论列表(0)

  1. 暂无评论