I have a List of Post with Pagination that I subscribe to the query parameter ?page=
to recalled the service API
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
const page = params['page'];
// on query parameter change, call the API service here
});
}
Now, I have a new requirement where User can also filter the list by selecting Category dropdown using Reactive Form.
Using Reactive Form, I can subscribe to the observer using this code here
onChanges(): void {
this.myForm.get('category').valueChanges.subscribe(val => {
// on form value change, call the API service here
});
}
My question is, how can I simplify this using Angular and RXJS?
The method in the example above not really DRY because the are calling the same API, only with different request parameter
Thanks.
You can use the combineLatest
operator:
ngOnInit(): void {
combineLatest(
this.route.queryParams,
this.myForm.get('category').valueChanges
).subscribe(([{ page }, category]) => {
// on any change call the API service here
});
}
Side note: Don't forget to unsubscribe in the onDestroy
hook, or use the takeUntil
operator