在我的Angular应用程序引导之前,我正在使用APP_INITIALIZER
令牌在页面加载上执行某些操作。我用于该逻辑的服务取决于我CoreModule
中的其他服务。
我知道这个错误正在发生,因为我正在将AuthService
注入我的AppService
,但是我不明白为什么这应该重要。 AuthService
不会注入AppService
,那么它是如何循环依赖的呢?
这是我的错误:
> 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)
这是我的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 {}
以下是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();
});
});
}
}
有人知道为什么会出现这样的错误吗?
修改(AuthService
的依赖关系):
constructor(
private ref: ApplicationRef,
private router: Router,
private http: HttpClient,
// Other custom services that are NOT imported into AppService...
) {}
答案 0 :(得分:3)
您向APP_INITIALIZER
提供依赖于AppService
依赖于AuthService
ApplicationRef
的{{1}}的工厂,该ApplicationInitStatus
取决于依赖于{APP_INITIALIZER
的{{1}} var map = new google.maps.Map(mapWrapperElem, mapOptions);
map.addListener("click",function(event){
// Do stuff
});
1}} ... et voila
请参阅第398页的https://github.com/angular/angular/blob/5.2.9/packages/core/src/application_init.ts和https://github.com/angular/angular/blob/5.2.9/packages/core/src/application_ref.ts