gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:03:51 27 4
gpt4 key购买 nike

假设我在我的应用程序上有一个路由,如 /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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com