【问题标题】:Firestore only returns last docFirestore 仅返回最后一个文档
【发布时间】:2021-02-04 15:21:56
【问题描述】:

我正在使用 AngularFirestore 和 NgRx,我有一个问题,当我对同一个方法有多个请求时,只有最后一个得到满足。我该如何解决这个问题?

数据库方法

// Using: import { AngularFirestore } from '@angular/fire/firestore';
getUnit(unitId: string): Observable<Unit> {  
  const unit$ = this.afs
    .collection<Unit>(constants.dbCollections.units)
    .doc(unitId)
    .snapshotChanges()
    .pipe(map((x) => x.payload.data()));

  return unit$;
}

使用多个 ID 正确调用此方法。

效果

loadUnit = createEffect(() =>
  this.actions$.pipe(
    ofType(unitActions.loadUnit),
    switchMap(({ unitId }) => {
      console.log('EFFECT CALL: ' + unitId);
      return this.dbService.getUnit(unitId).pipe(
        map((unit) => {
          console.log('EFFECT MAP: ID' + unitId, unit);
          return unitActions.unitLoaded({ unit });
        })
      );
    })
  )
);

此日志:

EFFECT CALL: re_demo_d4_c01_u01
EFFECT CALL: re_demo_d4_c01_u02
EFFECT CALL: re_demo_d4_c01_u03
EFFECT CALL: re_demo_d4_c01_u04
EFFECT CALL: re_demo_d4_c01_u05
EFFECT MAP: IDre_demo_d4_c01_u05 {thumbnail: "[url]", title: "10% 25% 50% 100%", introduction: Array(4), id: "re_demo_d4_c01_u05", name: "Procenten en breuken", …}
EFFECT MAP: IDre_demo_d4_c01_u05 {thumbnail: "[url]", title: "10% 25% 50% 100%", introduction: Array(4), id: "re_demo_d4_c01_u05", name: "Procenten en breuken", …}

MAP 被触发两次的事实是我不太了解的另一件事,但可以通过 DB 方法中的管道 sharedReplay 来解决。不过,这似乎不是眼前的问题。

如何获取所有文档?

我正在使用:

"@angular/fire": "^6.1.4",
"firebase": "^7.24.0",
"rxjs": "^6.6.3",
"@ngrx/core": "^1.2.0",
"@ngrx/effects": "^10.1.2",

【问题讨论】:

    标签: angular firebase google-cloud-firestore angularfire2


    【解决方案1】:

    高阶可观察映射是一个错误。 在我的效果中,我使用了switchMap,它取消了所有未完成的 observables。我想要的是使用mergeMap

    完成的所有可观察对象(并行)
    mergeMap(({ unitId }) =>
            this.dbService
              .getUnit(unitId)
              .pipe(map((unit) => unitActions.unitLoaded({ unit })))
    

    在这里找到详细解释:https://blog.angular-university.io/rxjs-higher-order-mapping/

    另一个奇怪的事情是内部 observable 发射了两次,这是通过在文档上添加 get 来解决的。

    .collection<Unit>(constants.dbCollections.units)
          .doc(unitId)
          .get()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2020-08-22
      • 2012-02-07
      • 1970-01-01
      相关资源
      最近更新 更多