微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

解决由于APP_INITIALIZER引起的循环依赖性

如何解决解决由于APP_INITIALIZER引起的循环依赖性

我有一个加载AuthenticationService的服务AngularFirestore。该服务已加载到RootComponent中。所有应用模块都被延迟加载到RootComponent中(它具有主要的router-outlet)。现在有许多子模块也可以加载AngularFirestore

我必须确保在加载组件和模块之前已初始化AuthenticationService(异步内容),因此我将其放入APP_INITIALIZER提供程序中。这会导致循环依赖 Cannot instantiate cyclic dependency! AngularFirestore

如果我不把它放在APP_INITIALIZER中,它可以工作,但是应用程序运行时没有初始化AuthenticationService

有没有解决的办法? (除了在所有组件中添加auth.initialize()

应用程序树:

AppComponent -> RootComponent(AuthenticationService) -> All Submodules(AuthenticationService,AngularFirestore)
// constructor of AuthenticationService
constructor(
    private auth : AngularFireAuth,private remoteconfig : AngularFireRemoteConfig,private keepalive: Keepalive,private idle: Idle,private toast : ToastService,private router : Router,private fs : AngularFirestore,private http : HttpClient,)
// providers in app.module.ts
{
  provide: APP_INITIALIZER,multi: true,useFactory: authFactory,deps: [
    AuthenticationService
  ]
}
// Factory for APP_INITIALIZER
export function authFactory(
  auth : AuthenticationService
) {
  return () : Promise<any> => auth.initialize();
}

致谢!

解决方法

因此,在经历了大量的github评论和无关的SO问题之后,我想出了一个解决方案,我在Github评论中略过了一个无关的问题。

TLDR :通过为AngularFirestore或整个应用程序为AuthenticationService创建新服务进行注入。我和后者一起去了。

了解问题所在:

据我了解,问题是因为我的AuthenticationService加载了AngularFirestore并将其作为其依赖关系树的一部分。现在,随后注入的AuthenticationServiceAngularFirestore都具有循环依赖关系,因为注入AuthenticationService会使AngularFirestore成为依赖树的一部分,而当我注入AngularFirestore之后它会创建两次AngularFirestore的注入。因此,错误。我可能完全错了,但是我认为这是问题所在。

解决方案:

AngularFirestore导入创建服务。我认为,这会将其移出依赖关系树,并将其作为服务注入,从而使其对于随后的AngularFirestore安全注入都可以。

// appfirestoreservice.ts
import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';

@Injectable({
  providedIn: 'root'
})
export class AppFirestoreService {
  
  public fs : AngularFirestore;
  public readonly collection = this._fs.collection;
  public readonly doc = this._fs.doc;
  public readonly createId = this._fs.createId;

  constructor(
    private _fs : AngularFirestore,) {
    this.fs = _fs;
  }
}
// App Initializer in AppModule
{
  provide: APP_INITIALIZER,multi: true,useFactory: initFactory,deps: [
    AppServiceInitializerService,RemoteConfigService,AuthenticationService,]
},

对于我来说,我不得不创建一个服务来仅加载RemoteConfigServiceAuthenticationService,因为它们必须一个接一个地初始化。

致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。