将 TranslateService 注入拦截器时的 Angular 循环依赖

问题描述 投票:0回答:3

我在将依赖项注入拦截器时遇到问题。我想将 TranslateService 注入 HttpErrorInterceptor,但出现循环依赖错误。当我删除 TranslateService 注入时,一切正常。

我已经在我的app.module.ts中声明了拦截器。 我的应用程序模块如下所示:

@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   BrowserAnimationsModule,
   CoreModule,
   HttpClientModule,
   TranslateModule.forRoot({
   loader: {
      provide: TranslateLoader,
      useFactory: HttpLoaderFactory,
      deps: [HttpClient],
   },
   defaultLanguage: 'pl-pl'
 }),
   AppRoutingModule,
   RouterModule,
   FormsModule,
   ReactiveFormsModule,
   ToastrModule.forRoot()
 ],
 providers: [
   {
     provide: HTTP_INTERCEPTORS,
     useClass: JwtInterceptor,
     multi: true
   },
   {
     provide: HTTP_INTERCEPTORS,
     useClass: HttpErrorInterceptor,
     multi: true,
     deps: [TranslateService, ToastrService]
   }
 ],
 bootstrap: [AppComponent]
})
export class AppModule { }

在 AppModule 中,我导入了 CoreModule,其中有一个包含拦截器的文件夹,我的 CoreModule 如下所示:

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  providers: [
    CookieService,
    NoAuthGuard,
    AuthGuard
  ]
})
export class CoreModule { }

我将登录页面放在AuthModule中,如下所示:

@NgModule({
  declarations: [LoginComponent, AuthComponent, ForgotPasswordComponent],
  imports: [
    CommonModule,
    AuthRoutingModule,
    RouterModule,
    SharedModule
  ],
  providers: [
    AuthService
  ]
})
export class AuthModule { }

在 Authmodule 中,我导入了 SharedModule,其中导出了 TranslateModule。 SharedModule 看起来像这样:

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    HttpClientModule,
    ReactiveFormsModule
  ],
  exports: [
    TranslateModule,
    ReactiveFormsModule
  ]
})
export class SharedModule { }

我找不到为什么登录页面出现循环依赖错误。

我的假设是,我已将 CoreModule 导入到 AppModule 中,在其中保留拦截器、守卫,并且我有 SharedModule,它是对所有功能模块的即兴发挥,我想保留例如那里有通用组件。

Błąd,jaki dostaję 致:

core.js:6162 ERROR Error: NG0200: Circular dependency in DI detected for InjectionToken HTTP_INTERCEPTORS. Find more at https://angular.io/errors/NG0200
    at throwCyclicDependencyError (core.js:216)
    at R3Injector.hydrate (core.js:11381)
    at R3Injector.get (core.js:11205)
    at HttpInterceptingHandler.handle (http.js:1978)
    at MergeMapSubscriber.project (http.js:1114)
    at MergeMapSubscriber._tryNext (mergeMap.js:44)
    at MergeMapSubscriber._next (mergeMap.js:34)
    at MergeMapSubscriber.next (Subscriber.js:49)
    at Observable._subscribe (subscribeToArray.js:3)
    at Observable._trySubscribe (Observable.js:42)
angular ngx-translate cyclic-dependency
3个回答
12
投票

您遇到的问题是,对于

TranslateModule
的初始化,您依赖于
HttpClient
,这意味着需要首先初始化
HttpClientModule
。这会导致
HttpErrorInterceptor
的初始化,因为拦截器是通过
HttpClientModule
初始化来初始化的。这会导致循环依赖,因为您的拦截器需要
TranslateService
。您可以通过在 HttpErrorInterceptor 中注入
Injector
来解决此问题,然后在需要时直接从注入器请求
TranslateService
。这样可以防止对初始初始化的循环依赖。

由于您没有为拦截器提供代码,因此这里是使用此方法的示例拦截器。

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(private readonly injector: Injector) {}

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    try {
      const translateService = this.injector.get(TranslateService)
      // log using translate service
    } catch {
      // log without translation translation service is not yet available
    }
  }
}

您仍然需要处理获取翻译服务失败的情况,因为加载翻译时可能会出现错误。


9
投票

根据 this GitHub 问题,一些人(包括我自己)能够通过删除

defaultLanguage
 中的 
TranslateModule.forRoot()

来解决该问题

我已经实现了我的语言模块如下:

@NgModule({
  imports: [
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      isolate: true
    })
  ],
  providers: [
    TranslateService
  ]
})
export class LanguageModule {
  public constructor(translateSvc: TranslateService, http: HttpClient) {
    translateSvc.onLangChange
      .pipe(
        switchMap((currentLang: LangChangeEvent) => zip(
          of(currentLang),
          http.get(`path/to/i18n/${currentLang.lang}.json`)
        ))
      ).subscribe(([currentLang, localizations]) => {
        translateSvc.setTranslation(translateSvc.currentLang, localizations, true);
      });

    translateSvc.use(translateSvc.getDefaultLang());
  }

然后导入到我的

CoreModule
:

@NgModule({
    imports: [
      CommonModule,
      HttpClientModule,
      BrowserAnimationsModule,
      LanguageModule,
      ...
    ],
    exports: [],
    declarations: [],
    providers: [
      ...
      {
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
      }
    ]
  })
  export class CoreModule {
    public constructor(@Optional() @SkipSelf() parentModule: CoreModule, private translateSvc: TranslateService) {
      this.translateSvc.use(environment.defaultLang)
    }
}

0
投票

您可以使用

HttpBackend
代替
HttpClient
。这样你就不会得到“循环 DI”错误,并且你将绕过所有拦截器。

loader: {
  provide: TranslateLoader,
  useClass: TranslationLoader,
  deps: [HttpBackend],
},
type TranslateFile = Record<string, string>;

const httpRequest = new HttpRequest<TranslateFile>(
  'GET',
  `/assets/${lang}.json?v=${appVersion}`
);

return this._httpHandler.handle(httpRequest).pipe(
  filter((httpEvent) => httpEvent instanceof HttpResponse),
  map((httpResponse) => (httpResponse as HttpResponse<TranslateFile>).body!)
);
© www.soinside.com 2019 - 2024. All rights reserved.