我有一个服务AuthenticationService来加载AngularFirestore。该服务在RootComponent中加载。所有的应用程序模块都是在RootComponent中延迟加载的(它有主router-outlet)。现在有许多子模块也加载AngularFirestore。
我必须确保在加载组件和模块之前初始化AuthenticationService (异步内容),所以我已经将其放入APP_INITIALIZER提供程序中。这导致了cyclic-dependency 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();
}致以问候!
发布于 2020-09-13 07:22:54
因此,经过大量的github评论和无关的问题之后,我想出了一个解决方案,我浏览了Github评论中一个无关的问题。
TLDR:通过为AngularFirestore或整个应用程序创建一个新服务来进行注入。我和后者一起去了。
理解问题:
据我所知,问题是因为我的AuthenticationService加载AngularFirestore并使其成为其依赖树的一部分。现在,任何后续的AuthenticationService和AngularFirestore注入都会产生循环依赖,因为注入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,
]
},就我的情况而言,我必须创建一个服务来加载RemoteConfigService和AuthenticationService,因为它们必须一个接一个地初始化。
致以问候!
https://stackoverflow.com/questions/63864156
复制相似问题