I am utilizing the APP_INITIALIZER
token to execute a task upon page load before my Angular application is initialized. The service responsible for this functionality relies on another service located within my CoreModule
.
The issue at hand seems to be about injecting the AuthService
into my AppService
. Although I cannot pinpoint why it's causing a problem. After all, AuthService
does not inject AppService
, so where does the circular dependency come from?
This is the error message I'm encountering:
> Uncaught Error: Provider parse errors: Cannot instantiate cyclic
> dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppModule in
> ./AppModule@-1:-1 Cannot instantiate cyclic dependency! ApplicationRef
> ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
> at NgModuleProviderAnalyzer.parse (compiler.js:19550)
> at NgModuleCompiler.compile (compiler.js:20139)
> at JitCompiler._compileModule (compiler.js:34437)
> at eval (compiler.js:34368)
> at Object.then (compiler.js:474)
> at JitCompiler._compileModuleAndComponents (compiler.js:34366)
> at JitCompiler.compileModuleAsync (compiler.js:34260)
> at CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:239)
> at PlatformRef.bootstrapModule (core.js:5567)
> at bootstrap (main.ts:13)
Below is my AppModule
:
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppService, AppServiceFactory } from './app.service';
import { CoreModule } from 'core';
@NgModule({
imports: [
// ...
CoreModule,
// ...
],
providers: [
AppService,
{
provide: APP_INITIALIZER,
useFactory: AppServiceFactory,
deps: [AppService],
multi: true
}
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {}
Here is the implementation of AppService
:
import { Injectable } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { AuthService } from 'core/services/auth/auth.service';
export function AppServiceFactory(appService: AppService): () => Promise<any> {
return () => appService.doBeforeBootstrap();
}
@Injectable()
export class AppService {
constructor(private authService: AuthService) {}
doBeforeBootstrap(): Promise<any> {
return new Promise(resolve => {
this.authService.isLoggedIn().then((loggedIn: boolean) => {
if (loggedIn) {
return resolve();
}
this.authService.refreshToken().pipe(
finalize(() => resolve())
).subscribe();
});
});
}
}
Does anyone understand why such an error is being triggered?
Edit (dependencies of AuthService
):
constructor(
private ref: ApplicationRef,
private router: Router,
private http: HttpClient,
// Other custom services that are NOT imported into AppService...
) {}