Issue
I am writing a simple UI application and I need to call API to get the product by id in a product-details component. Id I get from route params
Usually, I do something like this:
this.activatedRoute.params
.subscribe(params => {
if (params['primaryKey']) {
this.service.get(params['primaryKey'])
.subscribe(product => {
this.product = product;
});
}
});
And it works fine just looks a little bit ugly with these trees of subscribing. I wanna use more RxJS so it will look like this (console logs are just for demonstration):
this.product$ = this.activatedRoute.params
.pipe(filter(params => {
console.log('in filter', params);
return 'primaryKey' in params;
}),
map(params => {
console.log('in map', params);
return parseInt(params.primaryKey, 10);
}),
switchMap(primaryKey => {
console.log('in switch map', primaryKey);
return this.service.get(primaryKey);
}));
But it doesn't work this way until I subscribe to it in the end (it even doesn't trigger any of console logs)... why?
Solution
You start with an Observable, which then you pass through some functions (filtering, mapping, and so on).
However, you will not start observing it and collecting values until you call subscribe()
. You can move all logic to inside that function or extract it to RxJS operators, but you still that function at the end:
this.product$ = this.activatedRoute.params
.pipe(...)
.subscribe();
You can find more in the documentation on the subscribe function.
Answered By - Ćukasz Nojek
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.