A technique of getting data from a an API is to declare it like this in the service:
getItems$ = this.httpClient.get<Item[]>(this.url);
then either subscribe to it or utilize async in the consuming component.
How would you do this if the get call requires parameters like get by id?
EDIT: The above is an example of a declarative approach to working with RxJS streams. The getItems$
is a property.
So the question is, when using a declarative approach with a property defining the stream instead of calling a getItems(itemId)
method, how to you pass in parameters?
To handle any "parameters", you create another action stream using Subject or BehaviorSubject. The "parameter" is then emitted into the stream.
Here is an example from one of my applications.
// Handle product selection action
private productSelectedSubject = new BehaviorSubject<number>(0);
productSelectedAction$ = this.productSelectedSubject.asObservable();
product$ = this.productSelectedAction$
.pipe(
filter(id => !!id),
switchMap(selectedProductId =>
this.http.get<Product>(`${this.productsUrl}/${selectedProductId}`)
));
// Selected product was changed
changeSelectedProduct(selectedProductId: number): void {
this.productSelectedSubject.next(selectedProductId);
}
Here we create a BehaviorSubject with an initial value of 0. (You could instead use a Subject with no initial value.)
When the user picks a product (or however the specific product is determined) the id of that product is emitted into the productSelectedSubject
This code then uses a pipeline to react every time there is a new product Id emitted into the stream. The first operator in the pipeline filters out any invalid Ids. The switchMap then uses the emitted product Id to issue the http get.
I have a complete example of this that also sets up additional "parameters" for pagination here: https://github.com/DeborahK/Angular-ActionStreams