Initialize AngularJs app before calling the controllers

前端 未结 1 627
臣服心动
臣服心动 2020-12-21 18:01

I have an AngularJs application in which I want to load the messages and application version at the very beginning and save them in local storage, then use them in the contr

相关标签:
1条回答
  • 2020-12-21 18:32

    As the question already mentions, this is usually solved with router resolvers because the initialization of route controllers can be naturally postponed this way. Since AngularJS router uses hashbang mode by default, it can be used with non-SPA (and can be recommended for complex non-SPA widgets):

    resolve: { 
      l10n: (localisationService) => {
        return localisationService.getMessages(localisationService.language)
      }
    }
    

    The result can be optionally cached to avoid requests when language is unchanged.

    Additionally, route definitions can be processed to add common local dependency (l10n) to all routes automatically.

    The problem with global services that should be asynchronously initialized can also be solved in Angular 2 and higher with asynchronous bootstrapping and APP_INITIALIZER provider. AngularJS doesn't have this capability. As this answer explains, in order to implement this in AngularJS there should be two applications, where initializer application loads all necessary data and then bootstraps main application:

    angular.module('app', [/* ... */]);
    
    angular.module('appInitializer', [])
    .factory('loader', ($http) => {
      return $http.get('...').then((result) => result.data);
    })
    .factory('initializer', (loader, $document) => {
      return loader.then((data) => {
        angular.module('app').constant('l10n', data);
    
        $document.ready(() => {
          angular.bootstrap($document.find('body'), ['app']);
        });
      });
    });
    
    angular.injector(['ng', 'appInitializer'])
    .get('initializer')
    .catch((err) => console.error(err));
    

    Considering that in original code the language is defined dynamically with $scope.language, second option (initializer application) is not applicable, and this should be performed with first option (route resolvers).

    0 讨论(0)
提交回复
热议问题