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.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

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.