angulartypescriptangular17app-initializer

APP_INITIALIZER - TypeError: appInits is not a function


I would like to initialize some important values when my application starts (Angular v17).

app.config.ts:

export const appConfig: ApplicationConfig = {
    providers: [
        ConfigService,
        ...
        {
            provide: APP_INITIALIZER,
            useFactory: (init: ConfigService) => init.load(),
            multi: true,
            deps: [ConfigService, HttpClient]
        }
    ]
};

config.service.ts:

@Injectable({
    providedIn: 'root',
})
export class ConfigService {
    private http = inject(HttpClient);
    
    private _config: any;
    private _user: AppUser;
    
    public getConfigUrl(key: string): string {
        return this._config.urls[key];
    }

    public load(): Promise<any> {
        return new Promise((resolve, reject) => {
            this._user = new AppUser(); <-- normally a request to my node-express server
            this._config = 'test';
            resolve(true);
        });
    }
}

Then I got this error when I ran the application and did not understand why.

ERROR TypeError: appInits is not a function
    at \_ApplicationInitStatus.runInitializers (core.mjs:31069:32)
    at core.mjs:34973:28
    at \_callAndReportToErrorHandler (core.mjs:31146:24)
    at core.mjs:34971:20
    at \_ZoneDelegate.invoke (zone.js:368:26)
    at Object.onInvoke (core.mjs:14424:33)
    at \_ZoneDelegate.invoke (zone.js:367:52)
    at \_Zone.run (zone.js:130:43)
    at \_NgZone.run (core.mjs:14275:28)
    at internalCreateApplication (core.mjs:34948:23)

Solution

    1. Create a factory function as below:
    export function initializeAppFactory(init: ConfigService, http: HttpClient) {
      return () => init.load();
    }
    
    1. Provide the factory function to APP_INITIALIZER token:
    export const appConfig: ApplicationConfig = {
        providers: [
            ConfigService,
            ...
            {
              provide: APP_INITIALIZER,
              useFactory: initializeAppFactory,
              multi: true,
              deps: [ConfigService, HttpClient],
            }
        ]
    };
    

    Reference: APP_INITIALIZER