在 Angular NGRX 效果中链接两个 API 调用

Chaining two API calls in Angular NGRX Effect

我正在尝试解决一个小问题,但无济于事。我有一个用有效载荷调用的效果。我需要为结果调用 API,然后将该结果和有效负载传递给另一个 API。到目前为止我已经尝试过的是,它不起作用,因为它说动作应该 return 一个类型。

  @Effect()
  fetchSomething$ = this.actions
    .ofType(fromProfileAction.FETCH_POST)
    .map(action => action)
    .switchMap(payload => Observable.forkJoin([
      Observable.of(payload),
      this.xyzService.getXyz()
    ]))
    .switchMap(data => {
      const [action, xyz] = data;
      return this.postsService
          .abc(action.payload)
          .pipe(
            map(async (response: any) => {
              if (response.res) {
                const result = res.name + " - " + Xyz;
                action.payload.result = result;
              }
              return new fromProfileAction.FetchPostSuccess(action.payload);
            }),
            catchError(err => of(new fromProfileAction.FetchPostFailure({ err })))
          );
    });

任何指向正确方向的指针。

fetchSomething$ = this.actions
    .ofType(fromProfileAction.FETCH_POST)
    .map(action => action.payload)
    .switchMap(payload => this.xyzService.getXyz(payload)))
    .switchMap(data => {      
      return this.postsService
          .abc(data)
          .pipe(
            map(async (response: any) => {
              if (response.res) {
                const result = res.name + " - " + Xyz;
                action.payload.result = result;
              }
              return new fromProfileAction.FetchPostSuccess(action.payload);
            }),
            catchError(err => of(new fromProfileAction.FetchPostFailure({ err })))
          );
    });
@Effect() fetchSomething$ = this.actions .ofType(fromProfileAction.FETCH_POST) .map(action => action) .switchMap(payload => return  Observable.forkJoin([ Observable.of(payload), this.xyzService.getXyz() ])) .switchMap(data => { const [action, xyz] = data; return this.postsService .abc(action.payload) .pipe( map(async (response: any) => { if (response.res) { const result = res.name + " - " + Xyz; action.payload.result = result; } return new fromProfileAction.FetchPostSuccess(action.payload); }), catchError(err => of(new fromProfileAction.FetchPostFailure({ err }))) ); });

试试上面的代码。您必须 return 第一个开关映射中的结果。

你也可以

@Injectable()
export class SomeEffects {

  someAction$ = createEffect(() =>
    this.actions$.pipe(
      ofType(someEvent),
      exhaustMap((action) =>
        this.service1.get(action.someID).pipe(
          map((someObject) => someObjectLoaded({ someObject})),
        )
      )
    )
  );

  someObjectLoaded$ = createEffect(() =>
    this.actions$.pipe(
      ofType(someObjectLoaded),
      exhaustMap((action) => this.service2.get(action.someObject.someOtherID)
        .pipe(map((someOtherObject) => someOtherObjectLoaded({ someOtherObject} )))
      )
    )
  );

  constructor(
    private actions$: Actions,
    private service1: Service1,
    private service2: Service2
  ) {
  }
}