如何自动处理HTTP GET Observable响应的数组/含数组对象格式
重构方案
核心思路
- 移除手动指定的
startNode参数,通过代码自动识别响应格式:- 若响应本身是数组,直接使用
- 若响应是对象,先检查常见的数组键名(如
items、data、products等),再遍历对象所有属性找到数组类型的字段
- 用RxJS操作符优化异步流程,避免嵌套订阅,同时保留原有的本地端点降级逻辑
重构后代码
import { of } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; // ... getEndpoint(event: CustomEvent) { const mappedValues = mapValuesKeyBy(event.detail, 'name', 'value'); let endpoint = trim(mappedValues._endpoint) || 'http://localhost:4100/states'; const labelKey = trim(mappedValues._labelKey); const valueKey = trim(mappedValues._valueKey); const labelFormat = mappedValues._labelFormat; const hiddenColumns = trim(mappedValues._hiddenColumns); this.appService.get(endpoint, {}) .pipe( // 自动提取响应中的数组数据 map(response => this.extractArrayFromResponse(response)), // 若提取结果为空,降级请求本地端点 switchMap(data => { if (data.length === 0) { return this.appService.get('http://localhost:4100/states', {}).pipe( map(localResponse => this.extractArrayFromResponse(localResponse)) ); } return of(data); }) ) .subscribe(data => { const titleMap: TitleMapItem[] = map(data, value => ({ name: labelFormat ? this.jsf.parseVariables(labelFormat, value) : value[labelKey], value: value[valueKey] })); this.setTitleMap(event, titleMap); const tableConfig: AutoCompleteTableConfig = { labelKey, valueKey, hiddenColumns: hiddenColumns || [] }; this.setAutoCompleteList(event, data, tableConfig); }); } /** * 从响应中自动提取数组数据 * @param response HTTP接口响应数据 */ private extractArrayFromResponse(response: any): any[] { // 响应本身是数组,直接返回 if (Array.isArray(response)) { return response; } // 响应是对象,查找其中的数组字段 if (typeof response === 'object' && response !== null) { // 先检查常见的数组键名 const commonArrayKeys = ['items', 'data', 'products', 'results', 'list']; for (const key of commonArrayKeys) { if (Array.isArray(response[key])) { return response[key]; } } // 遍历所有属性,找到第一个数组类型的字段 for (const key in response) { if (response.hasOwnProperty(key) && Array.isArray(response[key])) { return response[key]; } } } // 没有找到有效数组,返回空数组 return []; }
关键改进点
- 自动格式识别:
extractArrayFromResponse函数处理两种响应格式,无需手动指定根节点 - 优化异步流程:使用
switchMap实现降级逻辑,避免嵌套订阅的回调地狱 - 健壮性提升:增加了空值检查和自有属性判断,避免意外读取原型链上的属性
内容的提问来源于stack exchange,提问作者Scott B
相关产品推荐
相关产品推荐

