【问题标题】:infinite loop in effect无限循环生效
【发布时间】:2023-03-28 19:50:01
【问题描述】:

编辑我有以下 =>

  @Effect()
  createMission$ = this.actions$.pipe(
    ofType<featureActions.CreateMissionRequest>(featureActions.ActionTypes.CreateMissionRequest),
    switchMap((action) =>
        this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId}))),
    switchMap((mission) => this.dataService.createMission(this.APIMissionFromMissionRoute(mission)).pipe(
        map(response => new featureActions.CreateMissionSuccess({response, mission})),
        catchError((error: HttpErrorResponse) => {
          return of(new featureActions.CreateMissionFailed({error}));
        }),
      )
    )
  );

目前没有服务器,但我用 observable 伪造了回复

  createMission(params: API_MODEL.IMissionAPI): Observable<API_MODEL.CreateMissionResponse> {
    return new Observable(observer => {
      setTimeout(() => {
        observer.next({
            result: {
                status: 2
            },
            missionID: {
                identifier: 41
            }
        });
        observer.complete();
      }, 120);
    });
  }

问题是,我的第二个 switchmap switchMap((mission) =&gt; this.dataService.createMission(this.APIMissionFromMissionRoute(mission)) 正在循环。这是因为我的第一个 switchMap 正在获取一个带有参数的选择器,当我的状态更新时,它会再次触发我的第二个 switchmap。

我想知道是否有办法以另一种方式获取我的当前状态。

我尝试了withLatest,但是我需要访问当前的action.payload才能得到我想要的,我无法将action传递给withLatest

【问题讨论】:

    标签: angular rxjs ngrx


    【解决方案1】:

    你应该使用 take 操作符让外部 observable 像这样完成 [否则正如你所说的 store 将被更新并触发执行选择器] -

    this.store$.pipe(select(MissionsStoreSelectors.getById(), {id : action.payload.routeId})).pipe(take(1)))
    

    【讨论】:

    • 我尝试使用 take,但得到以下结果:“MonoTypeOperatorFunction”类型的参数不可分配给“(outerValue:CreateMissionRequest,innerValue:any,outerIndex:number, innerIndex: number) => Observable'.
    • 啊,请在 select observable 上使用 take(1)。查看修改后的代码
    猜你喜欢
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2015-05-28
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多