首页 > 解决方案 > ngrx 效果 - 结合两个 API

问题描述

我有以下效果使用updateapi更新对象的一部分,然后我通过api获取整个对象findById,所以我曾经forkJoin将这两个api结合起来,但我希望findByIdapi在api的1秒后执行update,所以我用过 delay(1000),但它不工作

@Effect()
updateGeographicScope$ = this.actions$.pipe(
    ofType<conventionsActions.PatchGeographicScope>(conventionsActions.ConventionActionTypes.PATCH_GEOGRAPHIC_SCOPE),
    map(action => action.payload),
    exhaustMap(geographicScope => forkJoin(this.apiConvention.update(geographicScope),
        this.apiConvention.findById (geographicScope.externalId).pipe(delay(1000))).pipe(
            map(([first, convention]) => new conventionsActions.PatchSuccess({
                id: convention.externalId,
                changes: convention
            })),
            catchError(err => {
                console.error(err.message);
                return of(new conventionsActions.Failure({ concern: 'PATCH', error: err }));
            })
        ))
);

标签: typescriptrxjsngrxngrx-storengrx-effects

解决方案


您需要为此使用concatand timer。有了concat它,在开始下一个流之前完成第一个流。所以它进行更新,然后等待 1 秒,然后进行 findById。

@Effect()
updateGeographicScope$ = this.actions$.pipe(
    ofType<conventionsActions.PatchGeographicScope>(conventionsActions.ConventionActionTypes.PATCH_GEOGRAPHIC_SCOPE),
    map(action => action.payload),
    mergeMap(geographicScope => concat(
      this.apiConvention.update(geographicScope).pipe(switchMapTo(EMPTY)), // makes a request
      timer(1000).pipe(switchMapTo(EMPTY)), // waits 1 sec
      this.apiConvention.findById(geographicScope.externalId), // makes a request
    )),
    map(convention => new conventionsActions.PatchSuccess({
      id: convention.externalId,
      changes: convention
    })),
    catchError(err => {
      console.error(err.message);
      return of(new conventionsActions.Failure({ concern: 'PATCH', error: err }));
    }),
    repeat(), // make active after a failure
  )),
);

推荐阅读