You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NgRx Effect中将Action的Payload传入withLatestFrom的Selector

解决NgRx Effect中Action Payload传入动态选择器的问题

要将Action的Payload传入getMainCareuserMessagesConversationAppointmentsShift选择器,你需要先捕获当前Action,再动态生成对应的Store选择器Observable,而不是直接在withLatestFrom中传入静态参数。你提到的写法无法直接生效,因为withLatestFrom的静态参数会在管道初始化时确定,无法根据每个Action的Payload动态调整。

正确实现方式

通过switchMap先接收当前Action,再组合需要的Store流:

caregiverAcceptFetch = createEffect(() => {
  return this.actions.pipe(
    ofType(rdxMainCareuserMessagesConversationCaregiverAcceptFetch),
    // 先捕获Action,动态生成选择器流
    switchMap(action => {
      // 用Action的Payload作为参数调用选择器
      const shift$ = this.store.select(
        getMainCareuserMessagesConversationAppointmentsShift(action.payload?.index!)
      );
      const token$ = this.store.select(getTokenToken);
      
      // 组合Action、Token、Shift三个流的值
      return combineLatest([of(action), token$, shift$]);
    }),
    switchMap(([action, token, shift]) => {
      // 这里可以直接使用action、token、shift的所有数据
      return aschax.post(
        `/payment-request/${action.payload?.to}/${action.payload!.appId}/${action.payload?.cmId}`,
        null,
        { headers: { 'Authorization': 'Bearer ' + token } }
      ).then(res => ({
        type: RDX_MAIN_CAREUSER_MESSAGES_CONVERSATION_CAREGIVER_ACCEPT_FETCH_SUCCESS,
        payload: {
          index: action.payload?.index!,
          appid: action.payload?.appId!,
          to: action.payload?.to!
        }
      } as IAschacDispatch<IMainCareuserMessagesConversationCaregiverAcceptFetchSuccess>))
      .catch((err: AxiosError) => ({
        type: RDX_MAIN_CAREUSER_MESSAGES_CONVERSATION_CAREGIVER_ACCEPT_FETCH_ERROR,
        payload: {
          error: err.response?.data,
          index: action.payload?.index,
          appid: action.payload?.appId!
        }
      } as IAschacDispatch<IMainCareuserMessagesConversationCaregiverAcceptFetchError>));
    })
  );
});

关键说明

  1. 用switchMap捕获Action:只有先拿到当前Action的实例,才能用它的Payload作为参数动态调用选择器。
  2. 动态生成选择器Observable:getMainCareuserMessagesConversationAppointmentsShift是带参数的选择器,必须传入Action的Payload值才能生成对应的Store数据流。
  3. 组合多个Store流:使用combineLatest将Action、Token、Shift的数据流合并,确保在后续操作中能获取到所有需要的值。

内容的提问来源于stack exchange,提问作者Noah Bergh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:43:24