首页 > 解决方案 > 使用 RxJS 将一种对象类型转换为另一种对象类型

问题描述

我有以下型号:

export interface IdName { 
    id: number;
    name: string;
}

export interface Product { 
    id: number;
    name: string;
    currency?: string;
    additionalData: any;
}

我想在 Angular/Typescript 中将 Observable<Product[]> 转换为 Observable<IdName[]>。我试过了

getData() : Observable<IdName[]> {

        // Note: getProducts returns Observable<Product[]>

        this.productService.getProducts().pipe(
            return map((product: Product) => {
                {id: product.id, name: product.name}
            });
        );

    }

但是,它显示了一些语法错误。我该如何解决?

标签: angulartypescriptrxjs

解决方案


您放错了return语句和分号。

它应该是:

return this.productService.getProducts().pipe(
  map((product: Product) => {
    return {id: product.id, name: product.name}
  })
);

pipe()接受定义为operator(input => output)或扩展的操作列表(可变参数)operator(input => { return output; })


推荐阅读