AngularJS : Initialize service with asynchronous data

后端 未结 10 1761
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:09

I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:

myModule.service(\'MyService\', function($http) {
            


        
10条回答
  •  悲&欢浪女
    2020-11-22 03:34

    The "manual bootstrap" case can gain access to Angular services by manually creating an injector before bootstrap. This initial injector will stand alone (not be attached to any elements) and include only a subset of the modules that are loaded. If all you need is core Angular services, it's sufficient to just load ng, like this:

    angular.element(document).ready(
        function() {
            var initInjector = angular.injector(['ng']);
            var $http = initInjector.get('$http');
            $http.get('/config.json').then(
                function (response) {
                   var config = response.data;
                   // Add additional services/constants/variables to your app,
                   // and then finally bootstrap it:
                   angular.bootstrap(document, ['myApp']);
                }
            );
        }
    );
    

    You can, for example, use the module.constant mechanism to make data available to your app:

    myApp.constant('myAppConfig', data);
    

    This myAppConfig can now be injected just like any other service, and in particular it's available during the configuration phase:

    myApp.config(
        function (myAppConfig, someService) {
            someService.config(myAppConfig.someServiceConfig);
        }
    );
    

    or, for a smaller app, you could just inject the global config directly into your service, at the expense of spreading knowledge about the configuration format throughout the application.

    Of course, since the async operations here will block the bootstrap of the application, and thus block the compilation/linking of the template, it's wise to use the ng-cloak directive to prevent the unparsed template from showing up during the work. You could also provide some sort of loading indication in the DOM , by providing some HTML that gets shown only until AngularJS initializes:

    Loading the app.....

    Done loading the app!

    I created a complete, working example of this approach on Plunker, loading the configuration from a static JSON file as an example.

提交回复
热议问题