We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable:
@Injectable()
export class ProductService {
getAllProducts(): Observable<Product[]> {
return this.http.get('/products')
}
}
Within our Angular application, there are three separate components nested deep within the structure that all require access to the product list.
Our goal is to enable each component to make use of:
this.productService.getAllProducts().subscribe(products => ...)
However, this approach initiates three distinct HTTP requests, along with client-side JSON parsing, which is not efficient.
One common solution would involve retrieving the Product[]
data once at the outermost page and passing it down to each individual component. Yet, this method leads to cluttered code and increases the complexity of passing data down between components.
In a Java environment, I would simply synchronize access to the getAllProducts()
method and cache the result within the ProductService
, returning the cached data if available.
Is there a way to achieve a similar outcome in Angular/TypeScript that is both efficient and streamlined?