Search code examples
angulartypescript

Angular 18 APP_INITIALIZER does not add provided deps


I have an angular 18 project with standalone components and a boostraping:

main.ts:

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

appConfig.ts

import {
  APP_INITIALIZER,
  ApplicationConfig,
  provideZoneChangeDetection,
} from '@angular/core';
import { provideRouter, Router } from '@angular/router';

import { routes } from './app.routes';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideToastr } from 'ngx-toastr';
import { onAppStart } from './app.initialiser';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAnimations(), // required animations providers
    provideToastr(), // Toastr providers
    {
      provide: APP_INITIALIZER,
      useValue: onAppStart,
      multi: true,
      deps: [Router],
    },
  ],
};

app.initialiser.ts

import { Router } from '@angular/router';

export function onAppStart(router: Router): Promise<any> {
  return new Promise((resolve, reject) => {
    console.log(router);
    resolve(true);
  });
}

When running the app, router in app.initialiser.ts is undefined and i can't see why. Every deps I provide in app.config.ts is emtpy. What am I missing?


Solution

  • Do not use as param, instead inject the router in your function.

    Here you are:

    import { Router } from '@angular/router';
    
    export function onAppStart(): Promise<any> {
      const router = inject(Router);
      return new Promise((resolve, reject) => {
        console.log(router);
        resolve(true);
      });
    }
    

    And you can remove

    deps: [Router],