I have implemented a class called SearchFilter
class SearchFilter {
constructor(bucket: string,
pin: number,
qty: number,
category: string) {
}
}
When the user performs a search, I populate the filter into matrix params.
router.navigate(['filter', searchFilter]); //searchFilter is an instance
The resulting URL structure is as follows:
filter;bucket=MPC123;category=JOINT;qty=90;pin=9087
This functionality is utilized in another component where the parameter is mapped back to an Object
of type SearchFilter
. However, it is necessary to set the data types explicitly in this process.
const params = this.activatedRoute.snapshot.params;
const filter = this.getFilterFromParams(params);
getFilterFromParams(params) :SearchFilter {
const filter = new SearchFilter();
Object.keys(params).forEach((key) => {
switch(key) {
case 'pin':
case 'qty': filter[key] = Number(params[key]); break;
default: filter[key] = params[key];
}
});
return filter;
}
Looking at the code above, a custom mapping function is used to map the parameters back to an Object. Is there a more straightforward way to achieve this or is this a commonly used pattern?
I need to rely on URLs for user-friendliness, as users should be able to share URLs with different filters.