Application Initialization Error: appInits is not a valid function

When my Angular v17 application starts, I need to set some important values right away.

This is how it's done in app.config.ts:

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

Here is the config.service.ts code:

@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(); <-- usually a request to my node-express server
            this._config = 'test';
            resolve(true);
        });
    }
}

However, when I tried to run the application, I encountered an error that I couldn't figure out. It said:

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)

Answer №1

  1. To begin, create a factory function using the following code snippet:
export function initializeAppFactory(init: ConfigService, http: HttpClient) {
  return () => init.load();
}
  1. Next, assign the factory function to the APP_INITIALIZER token like so:
export const appConfig: ApplicationConfig = {
    providers: [
        ConfigService,
        ...
        {
          provide: APP_INITIALIZER,
          useFactory: initializeAppFactory,
          multi: true,
          deps: [ConfigService, HttpClient],
        }
    ]
};

For more information, you can visit the official documentation on APP_INITIALIZER.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The counterpart of the RxJS setTimeout operator

Looking for a RxJS operator alternative to set/clearTimeout in these circumstances: this.mouseEnterSubscription = this.mouseEnterStream .subscribe(() => { this.timeout = setTimeout(() => { void this.playVideo(); }, 500) }); this.mo ...

Tips for handling dropdowns within a formarray in Angular

https://i.stack.imgur.com/f7V4H.pngI'm currently attempting to dynamically select a dropdown value, but the issue I'm encountering is that when I select a value in the dropdown, I get an object out of it. From this object, I am trying to set the ...

What are some creative ways to emphasize certain dates?

Is there a way to customize mui-x-date-pickers to highlight specific days from a Date array with green filled circles around them? I am using new Date and wondering how to achieve this effect. Below is the code snippet I am currently working with: <Dat ...

Is it possible to utilize the returned value of a function within an if statement?

Is there a way to return the result of a function without needing to declare a variable? Can you return the result of a function in a single line? How can you return the result of a function inside an if statement? Is it possible to use a function's ...

Trouble with styling the Ngx-org-chart in Angular

I integrated the ngx-org-chart library into my Angular project, but I'm facing issues with the styles not applying correctly. Here are the steps I followed: I first installed the package using: yarn add ngx-org-chart Then, I added the ngx-org ...

"Comparing the use of single Angular libraries versus multiple libraries on npm

I am considering consolidating all my libraries (57 in total) into a single folder called @my-organisation/team. This is because each library has many dependencies on one another and managing versioning & dependencies separately would be difficult. After s ...

Determining the best method for change detection in Angular 2: Choosing between Observable, EventEmitter, and Dot Rule

Managing change detection in Angular2 can be approached in three different methods that I have observed. Utilizing Observables @Injectable() export class TodosService { todos$: Observable<Array<Todo>>; private _todosObserver: any; ...

Updating object properties in Typescript

I have written the following Angular 2 TypeScript code: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) ...

How do you implement a conditional radio button in Angular 2?

I am facing an issue with two radio buttons functionality. When the first radio button is selected and the user clicks a button, the display should be set to false. On the other hand, when the second radio button is chosen and the button is clicked, ' ...

Encountering TS 2732 error while attempting to incorporate JSON into Typescript

Having trouble importing a JSON file into my TypeScript program, I keep getting error TS2732: Can't find module. The JSON file I'm trying to import is located in the src folder alongside the main.ts file. Here's my code: import logs = requi ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Is it possible to create cloud functions for Firebase using both JavaScript and TypeScript?

For my Firebase project, I have successfully deployed around 4 or 5 functions using JavaScript. However, I now wish to incorporate async-await into 2 of these functions. As such, I am considering converting these specific functions to TypeScript. My conc ...

Using Typescript to set the image source from a pipe

I've been working on creating a custom pipe similar to the code below: @Pipe({ name: 'imagePipe' }) @Injectable() export class ImagePipe { constructor(public someService: SomeService, public storage: Storage) { } transform(value: ...

Improved with TypeScript 4.1: Fixed-Size String Literal Type

The latest updates from the TypeScript team have shown significant improvements in string literal typing (4.1 & 4.2). I'm curious if there's a way to define a fixed length string. For example: type LambdaServicePrefix = 'my-application- ...

How to transform an array of Objects into a regular array using IONIC technology?

I'm currently working on converting an Object array into a regular array in HTML without using the "let item of array" method. Despite my extensive googling, I haven't found a solution that works thus far. Why am I avoiding loops? Well, because ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Creating a dynamic form in Angular based on user input

I am in the process of creating a dynamic web form where the user's input will determine the subsequent form inputs that are generated. For example: <mat-form-field> <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="Typ ...

Strange occurrences observed in the functionality of Angular Material Version 16

Encountered a strange bug recently. Whenever the page height exceeds the viewport due to mat-form-fields, I'm facing an issue where some elements, particularly those from Angular Material, fail to load. Here's a GIF demonstrating the problem: GI ...

Exploring Angular Components with Jasmine and Karma while integrating third-party tools such as ExcelJS

Currently tackling the challenge of writing tests for a project using ExcelJS. The project runs smoothly in both build and production environments, but when attempting to incorporate unit tests for certain components, I'm encountering issues with Test ...

The absence of jQuery is causing an issue in the webpack +Angular 4+ Asp Core template

I am currently working on a project that was created using the VS 2017 Angular 4 + Asp Core template. I have decided to incorporate a jQuery plugin into my project, which requires me to import jQuery. In my .ts file, I have included the following line of c ...