Angular/Typescript中使用RxJS将Observable<Product[]>转为Observable<IdName[]>
存在的错误点
- return 语句位置错误:应该把整个
this.productService.getProducts().pipe(...)作为返回值,return不能放在pipe的参数列表中 - 流内数据类型匹配错误:
getProducts()返回的是Observable<Product[]>,管道中接收到的是Product数组,不是单个Product对象 - 箭头函数返回对象语法错误:直接用大括号包裹对象时,JS会将大括号识别为函数体块,要么给对象外层加小括号,要么在函数体内显式写return返回对象
修复后完整代码
import { map } from 'rxjs'; // 类内方法 getData() : Observable<IdName[]> { // 注:getProducts返回Observable<Product[]> return this.productService.getProducts().pipe( map((products: Product[]) => { // 调用数组原生map方法遍历转换每个元素 return products.map(product => ({ id: product.id, name: product.name })) }) ); }
也可以简化为隐式返回的写法,减少冗余代码:
getData() : Observable<IdName[]> { return this.productService.getProducts().pipe( map((products: Product[]) => products.map(p => ({id: p.id, name: p.name}))) ); }
内容的提问来源于stack exchange,提问作者developer
相关产品推荐
相关产品推荐

