无法使用 RxJS 6 和扩展运算符(Angular、Firebase 和 Observables)递归查询



我根据这个问题创建一个查询,该查询使用AngularFire从Angular 9应用程序中的firebase集合中检索一个随机项目。

该解决方案运行良好,除了查询返回0个结果外,我得到了预期的结果。如果发生这种情况,我想重复查询更改一些参数,直到我得到一个项,然后才返回一个可观察的项,以便在其他服务中订阅。我正在学习如何使用Observables和RxJS 6运算符,我认为expand运算符正是我所需要的。然而,我无法阻止expand退出递归循环,直到我获得所需的结果。

这是我的代码:

随机查询服务.ts

fetchDocumentoAleatorio(coleccionPath: string): Observable<any> {
const IdRandom = this.db.createId();
return this.consultaAleatorio(coleccionPath, '>=', IdRandom)
.pipe(expand((document: any) => document === null ? this.consultaAleatorio(coleccionPath, '<=', IdRandom) : EMPTY
), // I expect to repeat the query here changing '>=' to '<=' and using the same randomly generated Id
map((document) => { // The recursive loop never takes place since the map operator triggers even if consultaAleatorio() returns null one single time, sending that result to the subscribers
return publicacion.payload.doc.data();
}
));
}

consultaAleatorio(path: string, operador: any, idRandom: string): Observable<any> {
return this.db
.collection(path, ref => {
let query: firebase.firestore.CollectionReference | firebase.firestore.Query = ref;
query = query.where('random', operador, idRandom);
query = query.orderBy('random');
query = query.limit(1);
return query;
}).snapshotChanges()
.pipe(map((arrayDatos: any) => {
if (arrayDatos && arrayDatos.length) {
return arrayDatos[0];
} else {
return null; // It indeed reaches this point if the query returns empty results
}
}));
}

如果任何其他服务使用这个代码,它是这样做的:

订户示例服务.ts

private firebaseSubscriptions: Subscription [] = [];
publicacionAleatoriaSubject = new Subject<IpublicacionMiniatura>();
private publicacionAleatoria: IpublicacionMiniatura;
constructor(
private db: AngularFirestore,
private randomQueryService: RandomQueryService) {
}
fetchPublicacionAleatoria(): void {
this.firebaseSubscriptions.push(this.randomQueryService.fetchDocumentoAleatorio('publicaciones-meta')
.pipe(map((publicacion) => {
return {
//processes data
};
})
)
.subscribe((publicacionAleatoria: IpublicacionMiniatura) => {
this.publicacionAleatoria = publicacionAleatoria;
this.publicacionAleatoriaSubject.next(this.publicacionAleatoria);
}
));

总计:

  • 递归循环永远不会发生,因为即使consultaAleatorio()一次返回nullmap操作符也会触发,并将结果发送给订阅者
  • 当我在其他服务中订阅这个Observable时,除了所描述的情况外,它运行得很顺利,正如预期的那样,所以我认为问题在于我对如何处理expand运算符以实现我所需要的误解

提前感谢您抽出时间。

您可以使用retryWhen,如下所示:

.pipe(map((arrayDatos: any) => {
if (arrayDatos && arrayDatos.length) {
return arrayDatos[0];
} else {
throw new Error(); //  this causes it to be catched by retryWhen
}
}), retryWhen(errors=>errors.pipe(delay(100))); // retry after 100ms

Stacklitz

编辑:更正样本并添加stackblitz。

最新更新