javascript - AngularJS - 预加载应用程序设置

标签 javascript angularjs

假设我在我的应用程序上有一个路由,如 /config.json,它将返回一个对象,其中包含用户货币、用户区域设置等设置。

我想在应用程序启动时尽快预加载所有这些值,并且只预加载一次。

我认为 app.config() 部分就足够了,但我当时无法访问 $http 服务。你会如何处理这个问题?

编辑

我添加此尝试是为了提供更多上下文。

module.factory("test", function ($http) {

    // This is the service. It depends on the
    // settings, which must be read with a HTTP GET.
    return service = {
        settings: null,
        get: function(value) {
            return this.settings[ value ];
        }
    };

});

我试图返回一个延迟服务实例,即

return $http.get('/config').then(function(response){
    service.settings = response.data;
    return service;
});

但是,显然,不允许返回延期服务。

最佳答案

我可以想到一些方法来处理这个问题。

  1. 如果您使用诸如 php 之类的工具编写索引页面,您可以在浏览器处理页面之前将该文件的内容写入索引页面。

    <?php 
       //load the contents of the config file
       $configContents = file_get_contents('./config.json');
    ?>
    <html>
      <head>
        <!--all your script and css includes here-->
        <script>
           var configJson = <?php echo $configContents; ?>
           module.constant('config', configJson );
        </script>
        <!-- rest of your page... -->
    
  2. 基于 this post ,看起来你可以使用注入(inject)器来获取服务,然后你可以在加载所需数据后手动引导你的应用程序(基于 this documentation )。 (我还没有测试过这个...)

    angular.injector(['ng']).get('$http').get('./config.json').then(function(response){
        module.constant('config', response.data);
    
        //manually bootstrap your application now that you have gotten your data
        angular.element(document).ready(function() {
            angular.bootstrap(document, ['myApp']);
        });
    });
    

关于javascript - AngularJS - 预加载应用程序设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849655/

相关文章:

javascript - Angular -js :ng-model not working with searchable dropdown

node.js - 从 TeamCity 运行 Karma

angularjs - Angular 2 : How to link directly from the root view to a (grand)child view

javascript - 将 aspx 页面加载到 <ext :Panel>

javascript - 在javascript中的标题标签之间分组html

javascript - 根据屏幕大小和父 div 位置定位子 div

javascript - 如何通过下划线获取对象数组的唯一键?

javascript - 禁用 NestJS 中所有 POST 的状态 201

javascript - Jinja2 的 JS 替代方案,可在带有 AngularJS 的静态服务器上工作

angularjs - Angular 新路由器是 1.5 版本的一部分