Runtime Injection of Settings in Angular

Austin Fahsl
2 min readApr 3, 2022

--

Photograph taken by Jeremy Bezanger and published on https://unsplash.com

A dedicated SettingsService and settings.json file can be used to easily inject runtime settings into an Angular application.

The environment.ts file that Angular supports out of the box can only support compile-time settings. Some settings, such as API urls, make sense to load at runtime so that changing them does not require a code deployment. We can request a settings.json file with Angular’s HttpClient to accomplish this.

A few components are needed. First up is the settings.json file that contains the settings we want to load at runtime. Note the path of this file -src/app/assets/settings.json. Being in the assets folder will ensure that it is automatically copied to the output directory by the Angular CLI at build time.

To translate these settings to TypeScript, we’ll need a common settings interface. This will be injected into our components and services using its dedicated InjectionToken.

Next will be the service that will load the settings. It is only referenced by the AppModule and the application initializer.

With these parts complete, we can now set up the AppModule to use them.

Now we can utilize these settings in other services using Angular’s dependency injection. Because we used an APP_INITIALIZER to get the settings, they are available to use immediately in the constructor of the component or service.

And we’ve done it! This is a powerful tool. To change the root url of our api without rebuilding our entire Angular app, we can now change the apiUrl property in asset/settings.json, either manually or in our automated release pipeline. With this, we can support a “build once, release many times” model with our Angular frontend.

Check out the fully functional example repository at https://github.com/fahslaj/runtime-settings-injection.

--

--

Austin Fahsl
Austin Fahsl

Written by Austin Fahsl

Software Engineer, Thinker, and Serial Hobbyist

No responses yet