Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Last active January 14, 2022 19:11
Show Gist options
  • Save LayZeeDK/589a6a20a89a577284a0552b1cd2550f to your computer and use it in GitHub Desktop.
Save LayZeeDK/589a6a20a89a577284a0552b1cd2550f to your computer and use it in GitHub Desktop.
Providing a configuration as a static dependency.
import { InjectionToken } from '@angular/core';
// We create an interface for the configuration JSON object
export interface Configuration {
readonly apiUrl: string;
readonly timezone: string;
readonly websocketUrl: string;
}
// We use a dependency injection token to access the configuration
// in our application.
export const configurationToken = new InjectionToken('Configuration');
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { configurationToken } from './app/configuration';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
// Platform creation and bootstrapping of the application is delayed
// until we have loaded the configuration file.
fetch('/assets/configuration.json')
.then(response => response.json())
.then(configuration =>
platformBrowserDynamic([
{ provide: configurationToken, useValue: configuration },
]).bootstrapModule(AppModule))
.catch(error => console.error(error));
import { Inject, Injectable } from '@angular/core';
import { Configuration, configurationToken } from './configuration';
@Injectable()
export class TimeService {
constructor(
@Inject(configurationToken) private configuration: Configuration,
) {}
// Configuration is available synchronously since it's just an object
// that can be injected.
get timezone(): string {
return this.configuration.timezone;
}
}
@joelnotified
Copy link

Thank you for this! ⭐ Will be using it so that we can build once in Docker and apply different configs based on environment.

Found it via this blog post https://medium.com/angular-in-depth/handling-angular-environments-in-continuous-delivery-eeaee96f0aae

One thing though. I didn't get this to work out of the box, since configuration is the Reponse right?

Am I right in that I have to do this?

fetch(configurationPath)
    .then(async configuration =>
        platformBrowserDynamic([
            { provide: configurationToken, useValue: await configuration.json() },
        ]).bootstrapModule(AdminModule))
    .catch(error => console.error(error)); 

@LayZeeDK
Copy link
Author

LayZeeDK commented Mar 7, 2021

@joelnotified
Yes, you are right, we have to call Response#json when using fetch. Thanks for catching this mistake 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment