Issue
When building a service in Angular is there any advantage of using a method to return an observable from http.get rather than assigning the observable to a variable directly on the service.
For example does: getPerson = () => this.http.get<Person>(personUrl);
have any advantages over: person$ = this.http.get<Person>(personUrl);
Solution
Benefit of using a method: It is easier to pass parameters for parameterized queries. Using the declarative approach means that you need to use a signal or a Subject/BehaviorSubject to react to the parameter and issue the http get request.
Benefit of a declarative approach (just using a variable): It is easier to work with the variable. You can use other operators, such as combineLatest
. You can more easily pipe the result through additional operators in any of the components to do component-level sorting.
Here are two examples:
EXAMPLE ONE: Combining two observables to "look up" the category ID and add a category name for display in the UI:
productsWithCategory$ = combineLatest([
this.products$,
this.productCategoryService.productCategories$
]).pipe(
map(([products, categories]) =>
products.map(product => ({
...product,
category: categories.find(c => product.categoryId === c.id)?.name
} as Product))
),
shareReplay(1)
);
EXAMPLE TWO: Finding a specific product in the array of products returned from the http.get of all products.
private productSelectedSubject = new BehaviorSubject<number>(0);
productSelectedAction$ = this.productSelectedSubject.asObservable();
selectedProduct$ = combineLatest([
this.productsWithCategory$,
this.productSelectedAction$
]).pipe(
map(([products, selectedProductId]) =>
products.find(product => product.id === selectedProductId)
),
shareReplay(1)
);
Also, in future versions of Angular, it may be easier to use the declarative approach and then create a signal from the result using the new signal features for binding to the UI.
products = toSignal(this.products$, {initialValue: [] as Product[]});
Answered By - DeborahK
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.