ngrx效果-结合两个API

时间:2020-05-24 18:39:20

标签: typescript rxjs ngrx ngrx-store ngrx-effects

我具有使用update api更新对象的一部分的以下效果,然后我通过findById api获取了整个对象,因此我使用forkJoin来组合这两个对象api,但是我希望findById api可以在update api上执行1秒后执行,所以我使用了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 }));
            })
        ))
);

1 个答案:

答案 0 :(得分:0)

为此,您需要使用concattimer。使用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
  )),
);