I am using the APP_INITIALIZER
token to do something on page load before my Angular app is bootstrapped. The service I am using for that logic depends on another service I have in my CoreModule
.
I know this error is happening because of the fact that I'm injecting the AuthService
into my AppService
, however I can't see why that should matter. AuthService
does not inject AppService
, so how is it a circular dependency?
This is my error:
> 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)
Here 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 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 the user is logged in, resolve (do nothing).
if (loggedIn) {
return resolve();
}
// Otherwise, refresh the users token before resolving.
this.authService.refreshToken().pipe(
finalize(() => resolve())
).subscribe();
});
});
}
}
Anyone know why such an error occurs?
Edit (dependencies of AuthService
):
constructor(
private ref: ApplicationRef,
private router: Router,
private http: HttpClient,
// Other custom services that are NOT imported into AppService...
) {}