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 }
];