【问题标题】:Injecting ActivatedRoute gives cyclic dependency error注入 ActivatedRoute 会产生循环依赖错误
【发布时间】:2019-10-28 05:02:02
【问题描述】:

我正在尝试在 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);
    }
}

已经有类似的问题,但它们是关于 HttpInterceptor 的。这是一项常规服务。

在为@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 { }

【问题讨论】:

    标签: angular dependency-injection angular-activatedroute


    【解决方案1】:

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

    【讨论】:

    • 感谢您将我指向 Stackblitz。鼓励我创造一个最小的复制品。以后会用到:)
    【解决方案2】:

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

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

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

    providers: [ ContentService ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2018-03-03
      • 2019-02-21
      • 2017-03-24
      • 1970-01-01
      • 2019-12-03
      相关资源
      最近更新 更多