Angular中布尔判断触发TypeError:提供false而非流的解决咨询
问题修复方案
错误原因
你的代码中,当shouldUpdateMovements && count > 0条件不成立时,表达式返回的是布尔值false,但switchMap要求必须返回Observable、Promise、数组、可迭代对象这类可被流化的值,布尔值不符合要求,因此触发报错。
修复方式
方式1:使用三元表达式返回空数组
空数组会被RxJS自动转换为空Observable,符合switchMap的返回要求:
getPreloadPendingCountSuccess$ = createEffect(() => this.actions$.pipe( ofType(fromActions.GetPreloadPendingCountSuccess), switchMap(({ count, shouldUpdateMovements }) => { return shouldUpdateMovements && count > 0 ? [fromActions.GetPreloadPendingMovementsRequest()] : []; }) ) );
方式2:返回RxJS的EMPTY空Observable
需要先导入EMPTY,这种方式更明确表达“不发射任何值”的意图:
import { EMPTY } from 'rxjs'; getPreloadPendingCountSuccess$ = createEffect(() => this.actions$.pipe( ofType(fromActions.GetPreloadPendingCountSuccess), switchMap(({ count, shouldUpdateMovements }) => { if (shouldUpdateMovements && count > 0) { return [fromActions.GetPreloadPendingMovementsRequest()]; } return EMPTY; }) ) );
方式3:提前用filter过滤不符合条件的动作
直接在进入switchMap前过滤掉不满足条件的action,逻辑更清晰:
getPreloadPendingCountSuccess$ = createEffect(() => this.actions$.pipe( ofType(fromActions.GetPreloadPendingCountSuccess), filter(({ count, shouldUpdateMovements }) => shouldUpdateMovements && count > 0), switchMap(() => [fromActions.GetPreloadPendingMovementsRequest()]) ) );
内容的提问来源于stack exchange,提问作者binder
相关产品推荐
相关产品推荐

