angular - 在 Angular 和 RxJS 中的 http 调用后添加数据转换步骤
问题描述
问题:下面的方法是在 Angular 中使用 observables .pipe .map 或 .subscribe 在 RxJS 中执行此操作的好方法吗?
场景:从 http 调用获取数据后,我想在单独的(长而重的)转换步骤中使用这些数据,然后返回原始数据(例如表格)和转换后的数据(例如图表)。
首先我使用了嵌套订阅,然后发现这篇博客文章解释了如何避免这种情况。我试图将它应用到我的场景中,但不确定这是否是最好的方法?
// this would be in my service
fetchData(): Observable<any> {
return this.http.post<any>(this.url, this.body, this.options)
.pipe(
switchMap(response => {
// Received response object
const dataOrig = response;
return this.createChartData(response)
// Combine the dataOrig object and the resolved dataChart to a single object
.pipe(
map(dataChart => ({ dataOrig, dataChart }))
);
}));
};
createChartData(data: any) {
// do some heavy transformation with data here
let output = ['a', 100, 'b', 50]; // example output
return from(output); // not sure if I need an observable here at all
}
////////////////////////////////////////
// this would go later in the component
final = {
dataOrig: null,
dataChart: null
};
finalStep() {
this.fetchData()
.subscribe(({ dataOrig, chartData }) => {
// Update the view with the matching information
this.final.dataOrig = dataOrig;
this.final.dataChart = chartData;
});
}
解决方案
一般来说,我的建议是在服务中加入尽可能多的逻辑,包括数据转换。对我来说,主要原因是它使测试变得更加容易。
在您的情况下,看起来 POST 返回了一些您需要在应用程序中转换的数据。这种转换似乎是同步的,即它不需要对任何外部异步资源进行任何调用,所以我不明白你为什么需要switchMap
. 一个简单map
的应该做的工作。
所以,最后,我要做的或多或少是这样的
fetchData(): Observable<any> {
return this.http.post<any>(this.url, this.body, this.options)
.pipe(
map(response => {
const transformedData = this.createChartData(response);
return { response, transformedData }
})
)
}
createChartData(data: any) {
// do some heavy transformation with data here
// you do not have to return an Observable here
return resultOfTransformation
}
推荐阅读
- java - Java - 定义几个自定义异常而不重写每个异常(干)
- java - @ManyToOne 没有在 Child 表中保留 Parent FKey 列
- javascript - 如何处理对客户端反应应用程序的外部重定向?
- javascript - 为什么 .indexof() 返回 -1;当项目存在于给定数组中时?| 谷歌脚本
- mysql - MySQL 在另一个查询中使用查询
- symfony4 - 如何将 hydra apiplatform 文档转换为 Swagger 规范 (OAS3)?
- sql-server - 我的数据库中的数据显示为问号
- flutter - 在构建函数之外使用 BuildContext
- ruby-on-rails - 使用外键作为复合键的一部分
- sql - 每天将数据从一个 SQL Server 数据库复制到另一个 SQL 数据库