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

Angular Effect中使用takeWhile轮询后mySecondAction未触发

问题原因

你的轮询方法中,takeWhile默认不会发射导致条件不成立的最后一个值:当后端返回doesExist: true时,这个值不会被传递到下游,takeLast(1)也就拿不到任何数据,导致pollTillFileCreated返回的Observable没有发射任何值,后续的map操作符无法执行,因此mySecondAction始终不会被派发。

解决方案

修改pollTillFileCreated方法中的takeWhile,添加第二个参数true,让它包含触发停止条件的那个值:

private pollTillFileCreated(fileName: string): Observable<boolean> {
  return timer(0, 1000).pipe(
    concatMap(() => this.service.fileExist(fileName)),
    // 添加第二个参数true,保留触发停止的最后一个值
    takeWhile((doesExist: boolean) => !doesExist, true),
    takeLast(1)
  );
}

同时确认Effect的代码结构正确(当前结构没问题,确保操作符串联逻辑正确):

myEffect = createEffect(() =>
  this.actions$.pipe(
    ofType(Actions.myFirstAction),
    withLatestFrom(this.store.select(Selectors.fileName)),
    switchMap(([payload, fileName]) => this.pollTillFileCreated(fileName)),
    map(() => Actions.mySecondAction()),
    catchError((error) => of(Actions.errorAction(error)))
  )
);

当takeWhile的inclusive参数设为true后,doesExist变为true时这个值会被发射到下游,takeLast(1)能获取到该值,Observable正常完成,后续的map操作符就会执行,成功派发mySecondAction。

内容的提问来源于stack exchange,提问作者Tom Carmi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 10:05:36