NgRx效果仅侦听最后返回的可观察对象,忽略任何先前返回的可观察对象

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

我正在将我的应用同步到Firestore,正在听更改。应用启动后,它会立即向我的商店发送一些操作,以添加文档。我还有NgRx效果,等待添加操作被触发以执行一些代码,主要是从与该操作一起分发的文档的引用中获取其他2个文档。我返回一个forkJoin,并且效果仅完成最后返回的可观察到的结果,而忽略了所有过去的结果。

我已经尝试过许多RxJs运算符进行去抖动,合并等操作,但是结果相同。

负责同步文件的服务

fStore.collection<ReservationDocument>('reservations', query =>
            query.where('hotel', '==', hotel.ref)
          )
          .stateChanges()
          .subscribe(actions => {
            actions.forEach(action => {
              switch (action.type) {
                case 'added':
                  console.log(action.payload);
                  store.dispatch(AddReservation({ reservation: action.payload }));
                  break;
                case 'modified':
                  store.dispatch(ModifiyReservation({ reservation: action.payload }));
                  break;
                case 'removed':
                  store.dispatch(RemoveReservation({ reservation: action.payload }));
                  break;
              }
            });
          });

和效果

getClientAndHotel$ = createEffect(() =>
    this.actions$.pipe(
      ofType(ADD_RESERVATION),
      switchMap(
        (addReservation: {
          reservation: DocumentChange<ReservationDocument>;
        }) => {
          console.log('hello');
          return forkJoin([
            (addReservation.reservation.doc.get(
              'client'
            ) as DocumentReference).get(),
            (addReservation.reservation.doc.get(
              'hotel'
            ) as DocumentReference).get()
          ]).pipe(
            map(
              result => {
                console.log(addReservation.reservation.doc.ref.path);
                return {
                  type: UPDATE_RESERVATION,
                  client: ClientFromDocumentData(
                    result[0].data() as ClientDocument,
                    result[0].ref
                  ),
                  hotel: HotelFromDocumentData(
                    result[1].data() as HotelDocument,
                    result[1].ref
                  ),
                  reservation: addReservation.reservation
                };
              }
            )
          );
        }
      )
    )
  );

我希望forkJoin完成并调度一个动作,但是,无论触发了多少次效果,只有最后一个触发器才会调度该动作。我怀疑每次触发效果时,它只会覆盖订阅,而不必等待上一个订阅完成,但是我不知道如何解决此问题。

angular ngrx angularfire
1个回答
0
投票

正如对此问题的评论所述,您应该使用mergeMap而不是switchMap

switchMap将取消待处理的请求,而mergeMap将处理所有请求。如果请求的顺序很重要,请使用concatMap

https://rxjs-dev.firebaseapp.com/api/operators/mergeMap

https://rxjs-dev.firebaseapp.com/api/operators/switchMap

https://rxjs-dev.firebaseapp.com/api/operators/concatMap

© www.soinside.com 2019 - 2024. All rights reserved.