Angular NgRx中首个Action完成后携带返回数据派发第二个Action
实现方法
你可以根据代码耦合度需求,从以下两种标准NgRx写法里选择:
方案1:同Effect内顺序派发多Action
NgRx原生支持Effect单次返回多个按顺序执行的Action,不用额外监听动作,直接修改现有Effect的流处理即可:
searchEnterpriseEffect: Observable<Action> = createEffect( () => this.effectActions.pipe( ofType(EnterpriseActionsTypes.SEARCH_ENTERPRISE), switchMap((action: EnterpriseActions) => { return this.enterpriseService.getEnterpriseById(action.payload) .pipe( // 替换原map为switchMap,用于返回多Action的observable switchMap((enterprise) => of( new SearchEnterpriseActionSuccess(enterprise), // 直接取接口返回的enterprise.id作为参数派发新Action new SearchDemandeData(enterprise.id) )), catchError((err) => of(new SearchEnterpriseActionError(err.status))) ) }) ) );
该方案逻辑聚合度高,适合「查询企业成功后必须加载需求数据」的强关联场景,两个Action会按照传入顺序依次进入reducer和相关Effect流。
方案2:独立Effect监听成功动作
如果要拆分逻辑解耦,保留原有Effect不动,新增一个专门监听企业查询成功Action的Effect即可:
// 原有searchEnterpriseEffect代码完全不需要修改 searchEnterpriseEffect: Observable<Action> = createEffect( () => this.effectActions.pipe( ofType(EnterpriseActionsTypes.SEARCH_ENTERPRISE), switchMap((action: EnterpriseActions) => { return this.enterpriseService.getEnterpriseById(action.payload) .pipe( map((enterprise) => new SearchEnterpriseActionSuccess(enterprise)), catchError((err) => of(new SearchEnterpriseActionError(err.status))) ) }) ) ); // 新增独立Effect,监听成功动作后触发需求数据查询 triggerSearchDemandeEffect: Observable<Action> = createEffect( () => this.effectActions.pipe( ofType(EnterpriseActionsTypes.SEARCH_ENTERPRISE_SUCCESS), switchMap((successAction: SearchEnterpriseActionSuccess) => { // 从成功Action的payload里拿到已返回的enterprise对象id const targetEnterpriseId = successAction.payload.id; return of(new SearchDemandeData(targetEnterpriseId)); }) ) );
该方案耦合度低,后续如果企业查询成功后还要追加其他逻辑(比如权限校验、埋点上报、加载其他关联资源),只需要新增对应监听Effect即可,不需要改动原有企业查询的核心逻辑,适合中大型项目使用。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

