/ AngularJS

Loading server config into AngularJS on app start

It's pretty straight forward to set config settings, such as API Urls, in an angular.config() function - that's what it's there for.

The problem is that development and production will of course have different setting values, which are often maintained and managed server-side, and so using a static javascript file is not ideal.

So the question is, how to get server-side configuration into Angular?

angular.module('app', [
  .config(['dataServiceProvider', function(dataServiceProvider) {
          // How to set the API Url depending on the environment????

Can't you just download some json from the server?

That was my first thought.

The Angular startup process uses Providers to set up common settings across services. In the example above, the dataServiceProvider will ensure that all dataService objects have the correct API url.

However, using a request to the server to get the settings (essentially using $http) is an asynchronous call. The angular.config() function will continue on and, as far as Angular is concerned, the app is now fully configured and ready to go.

But our XHR request to get the configuration may not have responded in time. The app isn't ready to start!

We need a Provider, yes, but it needs to be there at application start.

The solution then, is to create a Provider server-side, which is pre-cooked with the configuration settings we want.

Dynamically creating an a Provider server-side

I generally use ASP.NET on the back-end, so this is an example implementation in the .NET world.

The key points that I like are:

  • Any <appSetting> key with a client: prefix is automatically available to the Angular app. This makes it nice and easy to add new settings as they arise.
  • There's no duplication of settings; if the server also needs the same setting, it can use it too.
  • Having a separate module for the config (client.config) allows any module that needs it to depend on it.
  • With a bit of refactoring, it's a reusable solution that can work with future projects!

Maybe something to make into a nuget package?