简体   繁体   English

如何从Angular中的服务器获取配置值?

[英]How to get config values from server in Angular?

My application needs some config values on application startup. 我的应用程序在应用程序启动时需要一些配置值。 Suggestions from the community is to store them as constant as separate module, preferably in separate .js file. 来自社区的建议是将它们作为常量存储为单独的模块,最好存储在单独的.js文件中。 This might work for me. 这可能对我有用。
However my configuration values are also stored on the server, and dont want to duplicate those on client side, so i was thinking of making server call to get those. 但是,我的配置值也存储在服务器上,并且不想在客户端重复这些配置值,因此我正在考虑通过服务器调用来获取这些值。
Im newbie to angular, is it valid design practice to make server call in module's config method? 我是新手,请问在模块的config方法中进行服务器调用是否有效? If yes then should i just use $http service to get the values from the server? 如果是,那我应该只使用$ http服务从服务器获取值吗?

    var main = angular.module('myapp', ['AdalAngular']);

    main.config(['$stateProvider',$httpProvider, adalAuthenticationServiceProvider', function ($stateProvider,$httpProvider,adalProvider) {

        // $stateProvider configuration goes here

        // ?????CAN I make server call here to get configuration values for adalProvider.init method below???

        adalProvider.init(
            {
                instance: 'someurl', 
                tenant: 'tenantid',
                clientId: 'clientid',
                extraQueryParameter: 'someparameter',
                cacheLocation: 'localStorage',
            },
            $httpProvider
            );

    }]);

    main.run(["$rootScope", "$state", .....
        function ($rootScope, $state,.....) {

            // application start logic

        }]);


    main.factory("API", ["$http", "$rootScope", function ($http, $rootScope) {

        // API service that makes server call to get data

    }]);

EDIT1 编辑1

So based on suggestions below I'm going with declaring constant approach. 因此,基于以下建议,我将声明恒定方法。 Basically I will have separate config.js file and during deployment process I will overwrite the config.js file with respective environment based config.js file. 基本上,我将拥有单独的config.js文件,在部署过程中,我将使用基于环境的相应config.js文件覆盖config.js文件。

Question
If have to 10 constants then i have to pass them separately to module.config(). 如果必须有10个常量,那么我必须将它们分别传递给module.config()。 Is it possible to declare constant value as JSON object and somehow read it in config function so I don't have pass 10 different parameters? 是否可以将常量值声明为JSON对象并以某种方式在config函数中读取它,所以我没有传递10个不同的参数?

angular.module('myconfig', [])
            .constant('CONFIGOBJECT','{Const1:somevalue,Const2:somevalue,Const3:somevalue,Const4:somevalue}');

and then how do I read the values in config method? 然后如何读取config方法中的值?

var main = angular.module('myapp',['myconfig']);
main.config(['CONFIGOBJECT',function(CONFIGOBJECT){

 ?? How do I read CONFIGOBJECT value that is a string not json object?

})

I'll describe the solution used in project that i was working on some time ago. 我将描述前段时间在项目中使用的解决方案。

It's true that you cannot use services in config phase, and it's also true, that you can use providers and constants while config phase. 这是真的,你不能配置阶段使用的服务,这也是事实,你可以配置阶段使用的供应商和常量。 So we used the next solution: firstly, we created simple object with config, like 因此,我们使用了下一个解决方案:首先,我们使用config创建了简单的对象,例如

var config = {
    someConfig1: true,
    someConfig2: false,
    someConfigEvents: {
        event1: 'eventConfig1',
        event2: 'eventConfig2'
    }
    etc...
}

Then we also declared angular value with jQuery lib: 然后,我们还使用jQuery lib声明了角度值:

app.value('jQuery', jQuery);

And now we cannot use services like $http, but we can use jQuery, so we just making ajax call to config server and extending our config: 现在我们不能使用$ http这样的服务,但是我们可以使用jQuery,因此我们只需对配置服务器进行ajax调用并扩展配置:

jQuery.ajax("path/to/config", { async: false, cache: false })
   .done(function (data) {
      var response = angular.fromJson(data)
      if (response) {
         angular.extend(config, response.returnData.data);
      } else {
         alert('error');
      }
   })
   .fail(function () {
      alertError();
   })
   .always(function () {
      appInit();
   });

Only providers are available during the config phase, not services. 在配置阶段仅提供程序可用,服务不可用。 So you can't use $http during this phase. 因此,在此阶段不能使用$ http。

But you can use it during the execution phase (in a function passed to run() ). 但是您可以在执行阶段使用它(在传递给run()的函数中)。

An alternative is to have some JavaScript file dynamically generated by the server, and defining the constants you want. 一种替代方法是由服务器动态生成一些JavaScript文件,并定义所需的常量。

Another alternative is to generate such a JS file during the build, based on some file that would be read by the server-side code. 另一种选择是在构建期间基于服务器端代码将读取的某个文件生成此类JS文件。

You cannot inject a service into the config section. 不能将服务注入config部分。
You can inject a service into the run section. 可以将服务注入run部分。

So, you cannot use - for example $http service to retrieve data from server inside config() , but you can do in inside run() , which initializes the provider's service. 因此,您不能使用-例如$http服务从config()内部的服务器检索数据,但可以在run()内部run() ,该操作会初始化提供程序的服务。

See also more complete answer here . 另请参阅此处的更完整答案。

Hope this helps. 希望这可以帮助。

UPDATE : 更新

Why string ? 为什么要string Why don't you simply use 你为什么不简单地使用

.constant('CONFIGOBJECT', {Const1:somevalue,Const2:somevalue,Const3:somevalue,Const4:somevalue}

for 对于

.constant('CONFIGOBJECT', '{Const1:somevalue,Const2:somevalue,Const3:somevalue,Const4:somevalue}'

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM