Currently, I am dealing with an Observable
I attempted to utilize the RxJS pipe operator on the Observable
this.foodService.getAllRecipes().pipe(
reduce((array: ChartData[], value: Recipe[], i: number) => {
const author = this.createOrFindAuthor(array, value[i]);
author.y += 1;
return array;
}, new Array<ChartData>())
).subscribe(data => this.chartData$ = of(data.sort((a, b) => b.y - a.y)));
}
The method getAllRecipes() returns the Observable
The variable this.chartData$ holds an Observable
Although I successfully achieved the desired result using the reduce function within the subscribe operator, where the graphs displayed the expected data, I was intrigued to explore performing the reduction as a pipeable operator. Here is the code excerpt showcasing the reduction being done in the subscribe block:
this.foodService.getAllRecipes().subscribe((data) => {
const list = data.reduce((arr: ChartData[], v: Recipe) => {
const author = this.createOrFindAuthor(arr, v);
author.y += 1;
return arr;
}, new Array<ChartData>());
this.chartData$ = of(list.sort((a, b) => b.y - a.y));
});
While attempting to integrate the subscribe block into the pipeable reduce operator, I encountered compile errors indicating that the method expected Recipe[] for the value. It left me pondering whether I was only receiving the Observable and needed to further process it. Is my understanding of how the pipeable operator functions on the Observable flawed?
For your reference, provided below are the models and the createOrFindAuthor function:
export class Recipe {
public Title: string;
public Author: string;
public Source: string;
public Page: number;
public Link?: string;
}
export class ChartData {
name: string;
y: number;
}
private createOrFindAuthor(array: ChartData[], recipe: Recipe): ChartData {
const name = (recipe.Author.length > 0 ? recipe.Author : 'UNKNOWN');
let found = array.find(i => i.name === name);
if (!found) {
const newData = new ChartData();
newData.name = name;
newData.y = 0;
array.push(newData);
found = newData;
}
return found;
}