Angular2项目中如何合并承载不同业务逻辑的两个RxJS表达式
单流整合实现代码
以下是合并后的完整RxJS管道实现,完全覆盖原有两个流的全部业务逻辑:
// 需提前从rxjs引入对应操作符:filter, tap, switchMap, of this.trafficTypeControl.valueChanges .pipe( // 复用原有公共的非空过滤逻辑,单次执行 filter(value => value !== null), // 处理非Campaign类型场景的同步清空逻辑 tap(value => { if (value === TrafficType.TRANSACTIONAL || value === TrafficType.BULK_SEND) { this.campaignControl.setValue(null); this.flightControl.setValue(null); this.campaigns = []; this.flights = []; } }), // 处理Campaign类型场景的异步数据拉取 switchMap(value => { if (value === TrafficType.CAMPAIGN) { return this.campaignsService.getUnpaginatedCampaignsWithinRange({ accountIds: this.currentUser.account ? this.currentUser.account.id : null, campaignStatuses: this.campaignStatusIds, rangeStartDate: this.rangeControl.value[0].toISOString(), rangeEndDate: this.rangeControl.value[1].toISOString() }); } // 非Campaign场景返回空值可观察对象,避免switchMap空返回异常 return of(null); }), // 仅在拉取到有效活动数据时执行赋值与日志打印 tap(campaigns => { if (campaigns) { console.log("TrafficType.CAMPAIGN :" + JSON.stringify(campaigns)); this.campaigns = campaigns; } }) ) .subscribe();
实现说明
- 消除了原写法中对同一个表单控件
valueChanges的两次独立订阅,减少重复的流初始化开销与内存占用 - 替换原第一个流中冗余的
switchMap:由于该逻辑块为纯同步副作用操作,无内部异步订阅需求,改用tap更符合RxJS操作符的语义规范,避免无意义的流值透传 - 为
switchMap分支补充了兜底返回值:原写法在值不等于Campaign类型时,回调没有明确返回可观察对象,容易触发运行时空值异常,补充of(null)兜底可保证流正常流转 - 为活动列表赋值逻辑增加空值判断,避免非Campaign场景下意外将
this.campaigns覆盖为null
内容的提问来源于stack exchange,提问作者Starbucks Admin
相关产品推荐
相关产品推荐

