无法实例化循环依赖!ApplicationRef("[ERROR - >]"):在./AppModule@-1:-1中的NgModule AppModule中

Sha*_*mor 6 angular

我已将此代码添加到我的app.module.ts中

    providers: [ AppConfigService,
            {
                provide: APP_INITIALIZER,
                useFactory: (config: AppConfigService) => () => config.getAppConfig(),
                deps: [AppConfigService],
                multi: true
            },
]
Run Code Online (Sandbox Code Playgroud)

得到这个错误

在此输入图像描述

问题:我已经使用ngx-permission pkg获得许可.我设置了路由权限方法.但是当我刷新页面时,主页上的时间重定向却停留在当前页面上.所以我试图在应用程序启动方法之前加载权限来解决此问题但是出现了此错误.

 config.getAppConfig() // call when application start up
Run Code Online (Sandbox Code Playgroud)

有任何想法请帮忙.其他解决方案也欢迎.

Bar*_*jen 25

当您APP_INITIALIZER的依赖项依赖于 Angular 服务时,可能会发生此错误,例如Router.

解决方案是延迟注入,通过将服务的构造函数更改为接受 a Injector,然后在构造函数之外解析该值。

示例AppConfigService

import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class AppConfigService {

  // Helper property to resolve the service dependency.
  private get _router() { return this._injector.get(Router); }

  constructor(
    //private _router: Router
    private _injector: Injector
  ) { }

  navigate() {
    this._router.navigate(['/']);
  }
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*mor 7

我已经用这个解决方案解决了我的问题

在 app.module.ts 中创建函数

export function loadConfig(appService: AppConfigService): Function {
    return () => appService.getAppConfig();
}

 AppConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: loadConfig,
            deps: [AppConfigService],
            multi: true
        },

issue into `HttpInterceptor` so i used injector for that
constructor(private inj: Injector) {
        super(
            inj.get(XHRBackend),
            inj.get(RequestOptions)
        );
}
Run Code Online (Sandbox Code Playgroud)