Question: Is the approach below a good way of doing it in Angular with RxJS using observables .pipe .map or.subscribe?
Scenario: After getting the data from a http call, I want to use this data in a seperate (long & heavy) transformation step and then return both - the original data (e.g. for tables) and the transformed data (e.g. for charts).
First I used nested subscriptions and then found this blog post exlaining how to avoid this. I tried to apply it to my scenario but not sure if this is the best way doing it?
// 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;
});
}