Within my Angular website, I am working with the following components:
product-api.service.ts:
export class ProductApiService {
constructor(private api: ApiHandlerService) { }
getProductsFromAPI() : Observable<Product[]> {
return this.api.get<Product[]>("/api/products");
}
}
product.service.ts:
export class ProductService {
constructor(private productApiSvc: ProductApiService) {}
getProducts() : Product[] {
this.productSvc.getProductsFromAPI().subscribe(
result => {
// return list here
}
)
}
}
product-list.component.ts
products: Product[];
constructor(private productSvc: ProductService) { }
ngOnInit(): void {
this.products = this.productSvc.getProducts();
}
In my component's class, I am utilizing the getProducts()
method from the product.service
class to fetch a product list. The issue arises as getProducts
returns type Observable<Product[]>
. How can I modify this to simply return Product[]
? Would it be beneficial to eliminate the wrapper of product.service.ts
and directly call getProductsFromAPI
from the list.component.ts
class? If so, what advantages does this offer? Thank you!