【发布时间】:2018-03-20 06:49:26
【问题描述】:
在我的 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...
) {}
【问题讨论】:
-
您是否在某处提供
AuthService?我看到AppService是。不确定不提供是否会导致您的问题。 -
在
CoreModule中提供,上例中AppModule中导入。 -
AuthService 的依赖是什么?
-
@NoémiSalaün 已编辑问题。
-
我不知道它在内部是如何工作的,但可能 ApplicationRef 在引导应用程序之前不存在,这就是它无法工作的原因,因为您尝试在引导之前实例化 AuthService 跨度>
标签: angular typescript