首页 > 解决方案 > 在 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;
        });
}

标签: angularrxjspipeobservablesubscribe

解决方案


一般来说,我的建议是在服务中加入尽可能多的逻辑,包括数据转换。对我来说,主要原因是它使测试变得更加容易。

在您的情况下,看起来 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
}

推荐阅读