2

我正在尝试在 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 { }
4

2 回答 2

1

尝试删除private injector: Injector并保留并在任何您想要使用private router: ActivatedRoute的地方调用变量。如果这仍然不起作用,我将需要 stackblitz 或其他地方的代码,以便我可以更深入地查看您的代码routerthis.router

于 2019-06-13T17:34:33.620 回答
1

在 APP_INITIALIZER 时间提供服务时,并非所有角度服务都已初始化。但是,ContentService 构造函数期望注入一个已初始化的 ActivatedRoute。这不知何故导致了循环依赖。

providers: [ { provide: APP_INITIALIZER, useFactory: loadContent, deps: [ContentService], multi: true }],

当服务像其他服务一样提供时,情况不再如此。

providers: [ ContentService ]
于 2019-07-16T10:21:04.817 回答