【发布时间】:2021-12-01 20:39:09
【问题描述】:
我从端点获取国家/地区,但为了以所需的形式显示数据,我使用 RxJS 地图运算符对其进行转换,其中我使用 reduce() 方法计算产品数组的长度和总费用。这段代码工作得很好,但问题是我不知道这是否是进行转换的正确方法。所以总结一下我的困惑,我有以下问题:
getCountries(): Observable<Country[]> {
return this.http.get<responseCountry[]>(this.countriesUrl).pipe(
map((countries: responseCountry[]) =>
countries.map((country: responseCountry): Country => {
const transformedCountryData: Country = {
name: country.name,
quantity_of_products: country.products.length,
totalExpense: this.calculateTotalExpenses(
country.products
),
};
return transformedCountryData;
})
)
);
}
calculateTotalExpenses(products: Product[]): number {
const initialValue = 0;
const totalExpense: number = products.reduce(
(previousValue, currentValue) => {
return (
previousValue +
currentValue.price * currentValue.quantity_for_month
);
},
initialValue
);
return totalExpense;
}
-
也许它是创建和使用
Country Class而不是interface的更好方法,因为我会将它用于类型检查,另外我可以将calculateTotalExpenses()方法移动到该类并且转换将发生在课堂而不是服务中。我对么?有没有更好的解决办法? -
做好准备,在这里我暴露了我的深刻知识差距:)当我像我一样转换数据时,如果使用
.reduce()的calculateTotalExpenses()方法稍后再给我结果(可能是由于产品很多) ,这不会导致totalExpense属性为undefined或其他什么吗? -
也许我应该在后端进行这种转换并提供现成的属性?在前端做这种数据转换是不好的做法吗?
【问题讨论】:
-
对不起,我不明白为什么你需要调用两次 map,因为 map 是一个数组函数,将 Array 转换为 Array
-
第一个
map是一个 rxjs 运算符,用于转换可观察值。这仍然为您提供responseCountry[]类型的参数,您仍然需要在其中映射每个元素。 @Lasha 我认为代码很好。继续使用 observables 以便在组件模板中使用| async。我只会删除过多的类型说明符以使代码更具可读性。 -
@Pieterjan 感谢您的回复。
标签: angular typescript rxjs angular-services