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
相关产品推荐
相关产品推荐

