Angular+TypeScript+RxJS 调用Trefle API发起多请求时遇到TS2355编译错误
问题根因定位
- 直接触发TS2355错误的原因:
mergeMap的回调标注了返回类型为Observable<any>,但回调内部只有类属性赋值语句,没有任何返回值,不符合TS的类型约束。 - RxJS使用逻辑偏差:
mergeMap的设计作用是将当前流的值映射为内部Observable,再合并内部流的输出,不是用来做副作用赋值的场景。原代码中把of(item.xxx)生成的Observable实例直接赋值给类属性,本质是把流对象而非实际业务值存到属性里,既没有实际作用,也完全不符合操作符的语义。 - 多请求实现逻辑错误:
fetchAllPlantData()中连续写了两个return语句,第一个return执行后,第二个return永远不会被触发,根本无法实现同时请求两个接口的目标。 - 属性定义缺陷:类中
growth属性的mm字段没有声明类型,也没有初始化值,运行时访问this.growth.minimum_precipitation.mm会触发空引用错误。
修复方案
1. 调整getPlantGrowth的流处理逻辑
将原代码中语义错误的mergeMap替换为专门用于副作用的tap操作符,不需要返回值,也不会触发类型错误:
import { pluck, concatMap, mergeMap, map, filter, first, elementAt, tap } from 'rxjs/operators' getPlantGrowth(): Observable<any> { return this.http.get(this.proxyurl + this.growthUrl + this.page) .pipe( pluck("data"), pluck("main_species"), tap((item: any) => { this.id = item["id"] this.common_name = item["common_name"] this.scientific_name = item["scientific_name"] this.growth.minimum_precipitation.mm = item["growth"]["minimum_precipitation"]["mm"] this.growth.maximum_precipitation.mm = item["growth"]["maximum_precipitation"]["mm"] }) ) }
如果需要将处理后的值继续往下游传递,也可以使用
map操作符,记得在回调中返回对应值即可。
2. 实现并发双接口请求
使用forkJoin操作符并发触发两个请求,等所有请求返回后合并结果:
import { forkJoin } from 'rxjs' fetchAllPlantData(): Observable<{growthData: any, plantList: any}> { return forkJoin({ growthData: this.getPlantGrowth(), plantList: this.getPlantImageIdName() }) }
该实现会同时发出两个HTTP请求,不需要串行等待,完全符合并发拉取数据的需求。
3. 补全类属性的类型定义
为类中的可选属性补充类型声明和初始化值,避免运行时空引用:
id?: number common_name?: string scientific_name?: string growth: { minimum_precipitation: { mm: number | null } maximum_precipitation: { mm: number | null } } = { minimum_precipitation: { mm: null }, maximum_precipitation: { mm: null } }
验证说明
- 所有RxJS回调的返回值完全匹配TS类型标注,不再触发TS2355编译错误。
- 两个接口请求会同时发起,两个请求全部返回后才会触发下游订阅,组件层拿到的结果会同时包含两个接口的提取数据。
- 所有副作用赋值逻辑放在语义匹配的操作符中,避免了
mergeMap的误用。
内容的提问来源于stack exchange,提问作者Dev Govindji
相关产品推荐
相关产品推荐

