【问题标题】:Returning Array of objects using RxJS map operator使用 RxJS 映射运算符返回对象数组
【发布时间】:2023-03-14 21:11:01
【问题描述】:

我有一个第三方 API,它返回如下数据 - 它是使用 HttpClient 从 Angular 服务调用的。

const someObject = {

    employees:[   

        {name:"XYZ",age:30},
        {name:"ABC",age:28},
    ]
}

现在我有一个interface,其结构如下 -

interface EmployeeData{

   campus:{

     property1:string;
     property2:string;

   };
   details:{

     name:string;
     age:number

   }
}

所以EmployeeData.details 完全模仿someObject.employees 结构

现在我想从我的服务中返回数据,如下所示 -

getData():Observable<EmployeeData[]>{

}

因此,员工 someObject 中的数组 应该映射到 EmployeeData.details

这应该返回为EmployeeData[].

我怎样才能做到这一点?

我尝试了以下方法,但它给出了不同的结果。

getData():Observable<EmployeeData[]> {


     return this.http.get<any>(url).pipe(

        tap(value => console.log(value)),
        map(data => data.employees),
        map(employees =>{

              return employees.map(employee =>{

                return{

                    details:{
                        name:employee.name,
                        age:employee.age,

                    }                       

                }           
            }
          }
        ) 

    }

它返回的是 -

details:{}
details:{}

但我想要的是:

{
    details:{}
}
{
    details:{}
}

有人可以帮忙吗?

【问题讨论】:

    标签: angular6 rxjs6


    【解决方案1】:

    如果你想用Observable&lt;EmployeeData&gt; 键入函数,你返回的 Observable 必须包含一个实现EmployeeData 接口的对象数组,这意味着你需要完全定义它们,而不仅仅是details 属性。

    如果此时不能定义所有属性,则必须使用带有as 关键字的类型断言。请注意,您将失去类型安全性并可能遇到错误,因为缺少的属性将是未定义的。

    getData(): Observable<EmployeeData[]> {
      return this.http.get<any>(url)
        .pipe(
          map(data => data.employees),
          map(employees => employees.map(employee => ({ details: employee } as EmployeeData)))
        );
    }
    

    在此处查看实际操作:https://stackblitz.com/edit/angular-msd6ym

    【讨论】:

    • 我已经更新了我的答案,它工作得很好,请参阅附加的 stackblitz 链接。
    猜你喜欢
    • 2018-12-13
    • 1970-01-01
    • 2023-04-08
    • 2018-03-12
    • 2019-07-06
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    相关资源
    最近更新 更多