Below is a sample of the service function I am working with:
getByIdWithCategory(id: number): Observable<Product> {
const category = new Category();
category.name = 'sample category';
return this.httpClient.get<Product>(this.baseUrl + `/${id}`)
.pipe(map(product => ({...product, category})));
}
In my template file, I retrieve the value returned from this function using the async pipe. However, I also need to obtain the category from the API, which requires subscribing. The challenge is in finding the best practice for unsubscribing from this call.
The following function meets my requirements perfectly. Nevertheless, I am struggling to unsubscribe from the API call used to retrieve the category.
getByIdWithCategory(id: number): Observable<Product> {
return this.httpClient.get<Product>(this.baseUrl + `/${id}`)
.pipe(
tap(product => {
this.categoryService.getById(product.id)
.subscribe(category => {
product.category = category;
});
})
);
}
My product class structure looks like this:
export class Product {
id: number;
title: string;
price: number;
description: string;
categoryId: number;
image: string;
category: Category;
}