Skip to solution
mediumFrontend

What is the APP_INITIALIZER token and how is it used to load configuration at startup?

1.0k views
01

Understand the problem

Explain app initialization and loading config files.

bootstrapdi
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

APP_INITIALIZER is a multi-provider token that accepts initialization functions. If a function returns a Promise or Observable, Angular waits for it to complete before finishing bootstrap, perfect for loading external environment configuration.

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

Loading runtime configuration at application startup
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { tap } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class ConfigService {
  private http = inject(HttpClient);
  private settings: any = null;

  get apiBaseUrl() { return this.settings?.apiUrl; }

  loadSettings(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.http.get('/assets/config.json').pipe(
        tap(cfg => this.settings = cfg)
      ).subscribe({
        next: () => resolve(),
        error: (err) => {
          console.error('Config failed to load', err);
          resolve();
        }
      });
    });
  }
}

// app.config.ts
import { ApplicationConfig, APP_INITIALIZER } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    {
      provide: APP_INITIALIZER,
      useFactory: (configSvc: ConfigService) => () => configSvc.loadSettings(),
      deps: [ConfigService],
      multi: true
    }
  ]
};
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 20 of 121 decoded in the Angular track. One more won't hurt.

Back to track