我正在尝试在 app-root 范围的服务中使用 ActivatedRoute,但出现我不理解且不知道如何进行故障排除的循环依赖错误。
在我的应用程序中,我有一项服务可以从顶级路由参数获取社区。
此服务在我的应用程序中的多个组件和其他服务中使用。
当我在构造函数中注入 ActivatedRoute 时,我得到
Error: Provider parse errors:
Cannot instantiate cyclic dependency! Router ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1
当我注入 Injector iteslf 然后在构造函数中获取 ActivatedRoute 时,我得到一个递归错误。当我稍后在某个方法中获得 ActivatedRoute 时,它确实按预期工作。
@Injectable()
export class CommunityService {
constructor(
private injector: Injector
// private router: ActivatedRoute => Cyclic dependency
) {
// const router = this.injector.get(ActivatedRoute); => InternalError: "too much recursion"
}
public getCommunity(): Community {
const router = this.injector.get(ActivatedRoute); // this should not be needed
const communityCode = router.snapshot.paramMap.get('community');
return getCommunityByCode(communityCode);
}
}
已经有类似的问题,但它们是关于 HttpInterceptors 的。这是一项常规服务。
在为@Alex创建 Stackblitz 时,我意识到我们在 APP_INITIALIZER 时间提供了社区服务。这是缺失的部分。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ContentService } from '@common/services/content.service';
export function loadContent(content: ContentService) {
return () => content.load();
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: [ { provide: APP_INITIALIZER, useFactory: loadContent, deps: [ContentService], multi: true }],
})
export class AppModule { }