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

What is the best way to eliminate the left margin entirely in CSS?

I am attempting to create an image view that fully covers the window, without any margins. I have tried various solutions such as setting the body margin and padding to 0, but they do not seem to work. body { margin: 0px; padding: 0px; } or *, html { ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

How can I customize the appearance of the file input button in Angular Material?

Despite browsing numerous similar questions, I have yet to find a solution to my issue. My setup includes Angular 11, Angular Material 8, and a file input structured like this: <div class="form-group"> <input #myInput type="fil ...

Leverage the power of an Angular component for repeated

Attempting to recycle an Angular component within the given tree structure. The desired component, existing-savings, is located in transfer-guide. Trying to utilize this component in retirement-contributions-information. What steps should be taken to ach ...

What is the method to retrieve Response Headers in cases of an empty response?

Currently, I am working with Angular2 and dotcms. My goal is to retrieve response headers after making a call to subscribe. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) .append('Access ...

Presenting CSV data in a tabular format using Angular and TypeScript

I am facing an issue with uploading a CSV file. Even though the table adjusts to the size of the dataset, it appears as if the CSV file is empty. Could this be due to an error in my code or something specific about the CSV file itself? I'm still learn ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

By default, Angular 6 now imports RxJS 6 operators seamlessly into its files

My Angular application extensively uses various RxJS 6 operators like filter, take, and takeUntil in almost all files. Importing these operators explicitly in every file is quite cumbersome. I wish there was a way to make them globally accessible. Imagine ...

Angular API snapshot error: The type 'IJobs' does not match the expected type 'IJobs[]'

Currently, I am in the process of learning and attempting to construct a job board using Angular 10. Although my API setup seems to be functioning properly, when navigating to the job detail page on Chrome, an error is displayed: ERROR in src/app/job-det ...

ng2-map - Double click to trigger two separate events

Currently, I am utilizing ng2-map to showcase a Google map in Angular 2. I have implemented the click event to capture any clicks made on the map. However, it seems that each click is generating two events rather than just one: 1) _.nk {latLng: _.F, pixel ...

"Troubleshooting alert: Encounter an error message saying 'process is not defined' when attempting to load the grpc package using proto-loader and grpc-js within a

Looking for help with integrating a typescript Vue.js component that needs to make a grpc call. The proto file can be found here: https://github.com/floydjones1/ts-node-grpc/blob/main/proto/random.proto Here is the component.vue code snippet: <script ...

What is the best way to sort an array of objects based on their properties?

I am working with an array of objects: let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}]; In addition to the array of objects, I have some arrays that will be used for filtering: let names = ["Jessy", "Megan"]; let prices = [300, ...

An unusual problem encountered while working with NextJS and NextAuth

In my NextJS authentication setup, I am using a custom token provider/service as outlined in this guide. The code structure is as follows: async function refreshAccessToken(authToken: AuthToken) { try { const tokenResponse = await AuthApi.refre ...

What is the best way to retrieve the href attribute when working with cheerio?

Is there a way to retrieve the link using Cheerio in this code snippet? <div class="someClass"> <a href="someLink">Link</a> </div> I attempted to do so, but unfortunately it was unsuccessful. let link = $(&a ...

Leveraging both the value from getStaticProps and the parameter in the component within NextJS

With this code snippet, I am attempting to load markdown files from a specific directory and pass them to a component that will display one of the markdown files based on a specified parameter. However, I am encountering an error when trying to use the com ...

Angular 12 experiencing CSS alignment issues

In my Angular component, I have the following CSS: .folders { border-left: 5px solid #b8744f; -moz-border-radius: 5px; -webkit-border-radius: 5px; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; /*CORRECTION NEEDED ...

There was a Runtime Error that occurred, stating a TypeError: It is not possible to access properties of an undefined value (specifically

I've encountered an issue with a donut chart implemented from react-apex charts. Every time I try to render the page containing the chart, an error occurs. However, if I make changes to a property of the chart, it renders without any errors on the fro ...

Is it possible to save an externally retrieved image locally using Angular?

I'm brand new to Angular and trying to work with a QR code image generated from the angularx-qrcode library. Here is the code snippet: <qrcode [qrdata]="'Your QR code data string'" [size]="256" [level]="'M'"></qrcode> ...

Do Not Activate the Android App with Deeplink in Ionic3

I'm currently using the ionic-plugin-deeplinks to enable deep linking within my app. Here are the steps I followed: $ ionic cordova plugin add ionic-plugin-deeplinks --variable URL_SCHEME=myapp --variable DEEPLINK_SCHEME=https --variable DEEPLINK_HOS ...