I get the whole menu from the web service, which is huge. It has > 10000 items. Firstly, I wanted to do request, based on what the user clicked, but since it's a menu, there'll be a lot of clicking and a lot of requests. So I figured, that it's best to just load the complete structure and then query that huge json, based on needs.
The idea was that when I firstly call the service, it checks if it has any data. If it doesn't, the http request gets made and the data mapped to a variable in service. Then when I need subcategories or whatever, I query that data and I don't need to make hundreds of http request JUST for the menu. But, I feel that I haven't done this well. It works, but it seems hacky. Especially the part where I expect that the data is present (see the getSubCategories
method below). Here's the code and please, feel free to notify me if there are any serious issues or provide ideas for making the code better:
getMainCategories() {
if (this.dataStore.length > 0) {
return of(this.generateMainCategories(this.dataStore));
} else
if (this.observable) {
return this.observable;
} else {
this.observable = this.http.get<ICategory[]>(`${this.apiUrl}/categories`).pipe(
tap(() => {
console.log('"getCategories" service called.');
}),
map((data) => {
this.observable = null;
this.dataStore = data;
return this.generateMainCategories(this.dataStore);
})
).share();
return this.observable;
}
}
getSubCategories(_id: string) {
if (this.dataStore.length > 0) {
return of(this.dataStore.find(x => x.TermCategoryUrl === _id));
} else {
return this.getMainCategories().pipe(
map((data) => {
return this.dataStore.find(x => x.TermCategoryUrl === _id);
})
);
}
}