如何解决在 Angular 和 RxJS 中调用 http 后添加数据转换步骤
问题:下面的方法是否是使用 observables .pipe .map 或 .subscribe 在 Angular 和 RxJS 中实现的好方法?
场景:从 http 调用获取数据后,我想在单独的(长和重)转换步骤中使用这些数据然后返回两者 - 原始数据(例如表格)和转换后的数据(例如图表)。
首先我使用嵌套订阅,然后发现这个 blog post 解释了如何避免这种情况。 我尝试将其应用于我的场景,但不确定这是否是最好的方法?
// 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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。