How to get config values from server in Angular?

6.5k Views Asked by At

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. 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? If yes then should i just use $http service to get the values from the server?

    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

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.

Question
If have to 10 constants then i have to pass them separately to 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?

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

and then how do I read the values in config method?

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

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

})
3

There are 3 best solutions below

0
On BEST ANSWER

You cannot inject a service into the config section.
You can inject a service into the run section.

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.

See also more complete answer here.

Hope this helps.

UPDATE:

Why 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}'

?

1
On

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

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

Then we also declared angular value with 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:

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();
   });
0
On

Only providers are available during the config phase, not services. So you can't use $http during this phase.

But you can use it during the execution phase (in a function passed to run()).

An alternative is to have some JavaScript file dynamically generated by the server, and defining the constants you want.

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.