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

Challenges associated with adding information to FormData in an Angular Net 5 Application

I'm currently working on developing an application using Angular 11 and .NET 5 and am facing some challenges while trying to implement the file upload feature. I have successfully managed to send pictures to the server, but I'm encountering issue ...

I'm currently utilizing CSS GRID to create a map layout, but I'm encountering an issue where the layout is not filling the entire screen. I'm wondering how I can achieve this in Angular

Here is the unique html code snippet for a layout that dynamically creates grids using json input: <!DOCTYPE html> <html lang="en"> <head> <title>Booking Page</title> </head> <body> <div ...

Utilize Angular 9 with an M1 Mac device

Struggling to get my project, which utilizes Node 12 and Angular 9, up and running on my new M1 Mac. I used nvm to install node and the latest npm version, then ran the command npm i -g @angular/cli@9 to install angular. Even though which ng confirms that ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Troubleshooting the issue of Angular 2 error: Cannot access the 'getOptional' property

Currently, I am navigating my way through angular 2 and attempting to define a service named searchservice. I want to inject this service in the bootstap part of my project: import {SearchService} from 'src/service'; Here is the code for the Se ...

What strategies can be implemented to avoid re-rendering in Angular 6 when the window is resized or loses focus?

I am currently working with a component in Angular 6.0.8 that consists of only an iframe element. Here is the code in page.component.html: <iframe [src]="url"> The logic for setting the URL is handled in page.component.ts: ngOnInit() { this.u ...

Prevent clicking outside the bootstrap modal in Angular 4 from closing the modal

Just starting out with angular4 and incorporating bootstrap modal into my project. I want the modal to close when clicking outside of it. Here's the code snippet: //in html <div bsModal #noticeModal="bs-modal" class="modal fade" tabindex="-1" rol ...

Roles in the Nebular system always have the granted status set to true by default

Hey there, I'm currently setting up Nebular to handle roles. Everything is working fine on the server side, but on the front end side, accessControl.isGranted() always returns true regardless of the role. Here's a snippet of the code I have been ...

Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct? import { Injectable } from '@angular/core'; import {Http, Headers} from '@angular/ht ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Is there a method to instruct angular-cli (for angular 2) to produce a minified version of css files?

When running "ng serve" in angular-cli, the generated css is not minified as expected. Is there a specific setting to configure in angular-cli-build or an additional plugin to install? This is the content of my angular-cli-build.js file: var Angular2App ...

Installing a 3rd party plugin in Angular using the Angular-cli tool

When attempting to install angular2-grid on my Angular-cli with version 2.0.0-rc.1, I followed the tutorial exactly as described but encountered an error. zone.js:101 GET http://localhost:4200/node_modules/angular2-grid/dist/NgGrid 404 (Not Found)sche ...

What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below: @Component({ selector: 'item-selector&apos ...

The issue arises when trying to use the map function on ctorParameters, which

I recently installed Angular2CLI from Bitbucket. After running npm install, ng build, and ng serve, I encountered an error when trying to access localhost:4200. Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities.paramet ...

Issue encountered: Upon executing 'ng add @angular/fire', an error was detected in the node_modules/firebase/compat/index.d.ts file while attempting to launch the Angular application

Recently, I decided to integrate Firebase into my project, but encountered a persistent error after installing the firebase module 'ng add @angular/fire' and running it with 'ng serve': Error: node_modules/firebase/compat/index.d.ts:770 ...

The module 'AppModule' is throwing an error due to the unexpected value 'Validators' being imported. Make sure to include a @NgModule annotation to resolve this issue

Currently, I have integrated Angular reactive forms into my application. Here is an excerpt from my app.module.ts file: import { HttpModule } from '@angular/http'; import { environment } from './../environments/environment'; import { ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

Exploring the Functionality of Algolia Places within a Next.js Application

Currently, I am working on integrating the Algolia Places functionality into my next.js project using TypeScript. To begin, I executed npm install places.js --save Next, I inserted <input type="search" id="address-input" placeholder ...

Tips on preventing pooling in Angular 5

service.ts: // Fetch all AgentLog logs using pooling method getAgentLogStream(): Promise<string> { const url = `${this.testCaseUrl}/logfile`; return Observable .interval(5000) .flatMap((i)=> this.http.get(url).toPromise().then(respons ...