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

Angular 10中NgRx Effect等待非初始值状态响应的问题

解决NgRx Effect等待状态非null的问题

你的问题出在withLatestFrom的使用上——它只会在LoadData动作触发的那一刻获取profile的当前值,如果此时profile是null,filter会直接过滤掉这个流,不会等待后续profile更新后再执行。

正确的做法是,针对每个LoadData动作,单独监听profile状态,直到它变为非null,再继续后续逻辑:

loadValues$ = createEffect(() =>
  this.actions$.pipe(
    ofType(myActions.myActionTypes.LoadData),
    map((action: myActions.loadData) => action.payload),
    // 替换withLatestFrom,改为针对每个action等待profile就绪
    switchMap(action => 
      this._store.pipe(
        select(fromOtherState.getBioData),
        // 过滤null/undefined值
        filter(profile => profile != null),
        // 只取第一个非null值,避免后续profile更新重复触发服务调用
        take(1),
        // 将action和就绪的profile组合
        map(profile => [action, profile])
      )
    ),
    switchMap(([action, profile]) => {
      return this.service
        .getDataValues(action["candidateID"], action["hasEnrolled"], profile)
        .pipe(
          map((data) => new myActions.LoadSuccess(data)),
          catchError((err) => of(new myActions.LoadFailed(err)))
        );
    })
  )
);

关键改动说明:

  • 用switchMap替代withLatestFrom:每个LoadData动作都会启动一个独立的流,专门监听profile状态的变化。
  • filter(profile => profile != null):忽略所有null/undefined的状态值。
  • take(1):拿到第一个非null的profile后就停止监听,避免后续profile更新重复触发服务调用。

内容的提问来源于stack exchange,提问作者Dev Developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:32:54