【问题标题】:Right way to transform data after fetching it获取数据后转换数据的正确方法
【发布时间】: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;
}
  1. 也许它是创建和使用Country Class 而不是interface 的更好方法,因为我会将它用于类型检查,另外我可以将calculateTotalExpenses() 方法移动到该类并且转换将发生在课堂而不是服务中。我对么?有没有更好的解决办法?

  2. 做好准备,在这里我暴露了我的深刻知识差距:)当我像我一样转换数据时,如果使用.reduce()calculateTotalExpenses()方法稍后再给我结果(可能是由于产品很多) ,这不会导致totalExpense 属性为undefined 或其他什么吗?

  3. 也许我应该在后端进行这种转换并提供现成的属性?在前端做这种数据转换是不好的做法吗?

【问题讨论】:

  • 对不起,我不明白为什么你需要调用两次 map,因为 map 是一个数组函数,将 Array 转换为 Array
  • 第一个 map 是一个 rxjs 运算符,用于转换可观察值。这仍然为您提供responseCountry[] 类型的参数,您仍然需要在其中映射每个元素。 @Lasha 我认为代码很好。继续使用 observables 以便在组件模板中使用 | async。我只会删除过多的类型说明符以使代码更具可读性。
  • @Pieterjan 感谢您的回复。

标签: angular typescript rxjs angular-services


【解决方案1】:

让我们从你的 3 点开始:

这是遵循的最佳实践,我们应始终避免在前端进行此类计算。您的后端 API 应返回转换后的数据

2 分:

不,除非数据本身存在 null/undefined 或某些计算错误,否则这永远不会发生。您正在返回一个 Observable 并且您将使用 subscribeasync pipe 来使用它。每当subscription 发生时,pipe 运算符都会处理它。

3 分:

据我所知,最好使用界面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    相关资源
    最近更新 更多