RxJs和redux-observable。当ajax成功或失败时附加值

时间:2018-01-11 20:42:31

标签: redux rxjs axios rxjs5 redux-observable

我有以下史诗:

export const changeTeamSubscriptionPlan = (braintreePlanId: string) => ({
  type: CHANGE_TEAM_SUBSCRIPTION_PLAN,
  braintreePlanId,
});

export const changeTeamSubscriptionPlanEpic = (action$: any, store: Store<ReduxState, *>) =>
  action$.ofType(CHANGE_TEAM_SUBSCRIPTION_PLAN)
    .mergeMap(({ braintreePlanId }) => {
      const state = store.getState();
      const { subscription_id } = state.payment.subscription;
      let request;
      if (subscription_id) {
        request = ajax(api.changeTeamSubscriptionPlan(subscription_id, braintreePlanId));
      } else {
        const [method] = state.payment.paymentMethods;
        request = ajax(api.createSubscription(braintreePlanId, method.token));
      }

      // I would like to emit another value ({ type: FETCH_TEAM }) no matter what happens 
      //(basically I try to invalidate the team data even if the request fails)
      return request
        .map(response => ({
          type: CHANGE_TEAM_SUBSCRIPTION_PLAN + SUCCESS,
          payload: {
            data: response.response,
            status: response.status,
          },
        }))
        .catch(error => Observable.of({
          type: CHANGE_TEAM_SUBSCRIPTION_PLAN + FAILURE,
          response: {
            data: error.xhr.response,
            status: error.xhr.status,
          },
        }));
    });

我想做的是,无论ajax来电是否以捕获结束,还是致电地图,我想追加其他价值。

我没有想法,所以我希望能得到帮助。

1 个答案:

答案 0 :(得分:0)

切换到原始操作符后,我发现我可以这样做:

  return request
    .map(response => ({
      type: CHANGE_TEAM_SUBSCRIPTION_PLAN + SUCCESS,
      payload: {
        data: response.response,
        status: response.status,
      },
    }))
    .catch(error => Observable.of({
      type: CHANGE_TEAM_SUBSCRIPTION_PLAN + FAILURE,
      error: mapToError(error),
    }))
    .concat(Observable.of({ type: 'CHUJ_TYPE' }));
当catch块触发时,

concat会追加值甚至

我最初使用的是自定义运算符,我会像catch那样工作,但会减少我应用中的样板:

Observable.prototype.mapFailure = function catchAndMapError(ACTION_TYPE, optionalPayload = {}) {
  return Observable.create(subscriber =>
    this.subscribe(
      value => subscriber.next(value),
      (error) => {
        try {
          const action = {
            type: ACTION_TYPE + FAILURE,
            error: {
              ...mapToError(error),
              ...optionalPayload,
            },
          };
          subscriber.next(action);
        } catch (e) { // catch mappings error
          subscriber.error(e);
        }
      },
      () => subscriber.complete(),
    ),
  );
};

它似乎与catch .....

的工作方式不同