代码之家  ›  专栏  ›  技术社区  ›  Ghassen

在调度具有NgRx效果的操作之前执行多个API调用

  •  0
  • Ghassen  · 技术社区  · 4 年前

    我用的是NgRx @Effect 为了达到某种效果,我需要执行2个API调用:第一个API调用的结果将用于第二个API调用,并且我希望分派一个 Action 第二个API调用为 payload 这种方式:

    @Effect()
    FetchDetails() {
      return this.actions.pipe(
        ofType(actions.SOME_ACTION),
        switchMap((action: SomeAction) => this.myService.getContext()),
        switchMap((ctx: Context) => this.myService.fetchDetails(action.id, ctx.requesterType)
          .pipe(
            map((response: Details) => new SetDetails(response)),
            catchError(err => {return of(new SetFetchDetailsError(err))})
          )
      )
    }
    

    使用双人床 switchMap 像这样我无法访问 action.id

    2 回复  |  直到 4 年前
        1
  •  1
  •   Anton Marinenko    4 年前

    只需在管道内部执行此操作:

    @Effect()
    FetchDetails() {
      return this.actions.pipe(
        ofType(actions.SOME_ACTION),
        switchMap((action: SomeAction) => this.myService.getContext().pipe(
          switchMap((ctx: Context) => this.myService.fetchDetails(action.id, ctx.requesterType)
        ))
          .pipe(
            map((response: Details) => new SetDetails(response)),
            catchError(err => {return of(new SetFetchDetailsError(err))})
          )
      )
    }
    
        2
  •  0
  •   Emilien    4 年前

    也许您需要一个新函数,它将调用 getContext()

    getContextAction(action: SomeAction): Observable<any> {
      return this.getContext().pipe(
        map(ctx => { action, ctx });
    }
    

    然后

    @Effect()
    FetchDetails() {
    return this.actions.pipe(
      // ...
      switchMap((action: SomeAction) => this.myService.getContextAction(action)),
      switchMap((value) => this.myService.fetchDetails(value.action.id, value.ctx.requesterType)
      // ...
    }
    

    您还可以编辑当前函数 getContext() 以返回给定的操作。

        3
  •  0
  •   Ghassen    4 年前

    concatMap 接线员:

    @Effect()
        FetchApiDetails() {
            return this.actions.pipe(
                ofType(apis.FETCH_SELECTED_API_DETAILS),
                concatMap((action: FetchSelectedApiDetails) =>
                    this.contextInit.getContext()
                        .pipe(
                            switchMap((ctx: Context) => this.apisManagementService.fetchApiDetails(action.apiId, ctx.requesterType)
                                .pipe(
                                    map((response: ApiDetails) => new SetApiDetails(response)),
                                    catchError(err => {
                                        return of(new SetFetchApiDetailsError(err))
                                    })
                                )
                            ),
                            catchError(err => {
                                console.log('An error happened when fetching context ' + err);
                                return of(err);
                            })
                        )
                )
            );
        }