Utilizing useClass in Angular's APP_INITIALIZER

Before my application starts up, I require some API data and am currently handling it with APP_INITIALIZER and useFactory. However, I aim to enhance the structure by separating all the code from app.module.ts:

app.module.ts

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { httpInterceptorProvider, appInitProvider } from '@core';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        AppRoutingModule,
        HttpClientModule
    ],
    providers: [
        httpInterceptorProvider,
        appInitProvider
    ],
    bootstrap: [AppComponent]
})

export class AppModule { }

@core/init/index.ts

import { APP_INITIALIZER } from '@angular/core';
import { InitService } from './init.service';

export const appInitProvider = [
    { provide: APP_INITIALIZER, useClass: InitService, multi: true }  
];

@core/init/init.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { SettingsService } from "@core";

@Injectable()
export class InitService implements Resolve<any> {
  
    constructor(
        private _http: HttpClient,
        private settings: SettingsService
    ) {}

    resolve() {
        const promise = this._http.get("/API")
        .toPromise()
        .then((data: any) => {
            this.settings.setSettings(data);
            return data;
        });
        return promise;
    }

}

During this process, I encounter an angular error:

TypeError: this.appInits[i] is not a function at ApplicationInitStatus.runInitializers

I have implemented a similar setup for the http interceptor, which works seamlessly without any issues.


EDIT: The accepted answer is the appropriate approach. Additionally, I had to make some adjustments to the provided code in order to get it working. Below is the final index.ts:

import { APP_INITIALIZER } from '@angular/core';
import { InitService } from './init.service';

export const appInitProvider = [
    InitService,
    { provide: APP_INITIALIZER, useFactory: (service:InitService)=>{return () => service.resolve()}, deps: [InitService], multi: true }
];

Answer №1

Instead of relying on useClass, consider utilizing useFactory

Give this a shot:

import { APP_INITIALIZER } from '@angular/core';
import { InitService } from './init.service';
export const appInitProvider = [
    { provide: APP_INITIALIZER, useFactory: (service:InitService)=>{return InitService.resolve()}, deps: [InitService], multi: true }  
];

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

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

Angular2 can enhance your webpage with a <div> element that covers the entire screen

While working on my Angular2 application, I encountered a challenging issue that I can't seem to resolve or find a solution for. Take a look at this image of my page: https://i.stack.imgur.com/b6KlV.png Code: content.component.html <app-header& ...

Mapping a JSON array within a static method in Angular2 and TypeScript

Struggling with the syntax to properly map my incoming data in a static method. The structure of my json Array is as follows: [ { "documents": [ { "title": "+1 (film)", "is-saved": false, ...

Is there a way for me to determine when a user has signed in for the first time?

Issue at Hand I am facing an obstacle in detecting when a user initially connects to Google on my app using Firebase. The method I am currently utilizing is auth.signInWithPopup(googleProvider);. To address this query, I delved into the documentation and ...

The meta title is not visible in the view page source, but it can be found when inspecting the webpage

Struggling to make my meta tags dynamic by integrating angular universal was quite a journey. Despite facing numerous challenges, I managed to successfully incorporate angular universal into my project. Running the project using npm run dev:ssr seemed prom ...

Ways to transfer JavaScript arguments to CSS style

Currently, I am developing a web service using Angular and Spring Boot. In this project, I have implemented cdkDrag functionality to allow users to place images in specific locations within the workspace. My goal is to maintain the placement of these image ...

Trouble locating feature module routes in Angular2

Trying to wrap my head around Angular2 routes. Here's the plunker link for reference: This. I'm facing an issue where it can't seem to locate the \heroes or \hero\:id route specified in the heroes-routing-module. Each time the ...

Making an HTTP request within a forEach function in Angular2

Encountering an issue while using the forEach function with HTTP requests. The _watchlistElements variable contains the following data: [{"xid":"DP_049908","name":"t10"},{"xid":"DP_928829","name":"t13"},{"xid":"DP_588690","name":"t14"},{"xid":"DP_891890" ...

Error: Android package not found when building a NativeScript app with TypeScript

I encountered the following error message: main-page.ts(15,26): error TS2304: Cannot find name 'android'. This error occurred after setting up a new NativeScript project using TypeScript. tns create demo --template typescript I then added the ...

Utilize NestJS to retrieve information from an observable gRPC service

One of the challenges I am facing is using gRPC service to facilitate communication between my microservices. Specifically, when receiving a response from the Grpc service, I need to apply some modifications and additional functionality before returning a ...

Fetching data from an API using Observables in Angular

I am facing a challenge with an API endpoint that returns an array of strings in JSON format. My goal is to display these contents on a webpage using an Angular Service. Below is the code snippet I have implemented so far (working with Angular 7): export ...

Bringing in the component's individual module

I encountered the error message in my Angular application - Can't bind to 'formGroup' since it isn't a known property of 'form' - and managed to resolve it by including the import import { AddEditModule } from './add.edit ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

Employing Multer and Express in conjunction with TypeScript

Overview Currently, I am working on a project that involves creating a user-friendly website where individuals can easily upload images. For this particular task, I have employed Node.js, React, Multer, and Typescript. Issue at Hand app.post('/admi ...

Error message: "Angular requires either importing or local installation"

For my ionic application development, I encountered an issue while trying to link pages together in the ionic creator. The error message on the .ts file is: typescript: src/pages/home/home.ts, line: 4 Individual declarations in merged declar ...

The age-old debate: Ngxs or Behavior Subject, which one should you go

I'm embarking on creating an admin panel for a Payment gateway product using Angular's latest version, working with a multitude of microservices. With experience in NGXS state management, as well as subjects and behavior subjects, I'm undeci ...

Ways to initiate a fresh API request while utilizing httpClient and shareReplay

I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup: apicaller.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http& ...

An issue arises in Angular 17 where the view does not refresh when using setInterval, accompanied by the NG0500

I am currently working on a countdown timer feature where I want to continuously update the 'seconds' value in real-time, but I'm facing an issue with the UI not reflecting these updates. Whenever I attempt to implement this without utilizi ...

An error has occurred during the Next.js build process: ReferenceError - The component is not defined

Encountering an error during the yarn build process, but no issues with yarn dev My Typography component is custom-made, and I utilize absolute imports with the baseUrl option in tsconfig.json next version: v9.5.2, typescript version: 3.9.7 See error ou ...