bradley
bradley

Reputation: 455

Best way to handle lots of optional paramaters in Angular

I have an Angular 4 component that displays data based on filter options that the user selects. I would like to save the filter options as paramaters in the url kind of like kibana.

I'm wondering whats the best way to handle all of these optional paramaters. I have a lot more than the 6 filter options I have in my example and its making the code a bit unwieldy.

Currently I'm subscribing to route.params and searching for each one with if statements. To create and navigate the url I'm subscribing to an event emitter, checking values of of a custom params class. Here is an exmaple of what it looks like

    this.route.params.subscribe((params: Params) => {
        if (params["filter1"]) this.params.filter1 = params["filter1"];
        if (params["filter2"]) this.params.filter2 = params["filter2"];
        if (params["filter3"]) this.params.filter3 = params["filter3"];
        if (params["filter4"]) this.params.filter4 = params["filter4"];
        if (params["filter5"]) this.params.filter5 = params["filter5"];
        if (params["filter6"]) this.params.filter6 = params["filter6"];
    });


    this.refreshParams.subscribe((params) => {
        let url = {};

        if (params.filter1) url["filter1"] = params.filter1;
        if (params.filter2) url["filter2"] = params.filter2;
        if (params.filter1) url["filter3"] = params.filter3;
        if (params.filter1) url["filter4"] = params.filter4;
        if (params.filter1) url["filter5"] = params.filter5;
        if (params.filter1) url["filter6"] = params.filter6;
        this.router.navigate(['/filters', url]);
    });

    selectFilter(filter1: Filter) {
       if (filter1) {
           this.params.filter1 = filter1;
       } else {
           this.params.filter1 = undefined;
       }
       this.refreshParams.next(this.params);
    }

Upvotes: 1

Views: 79

Answers (2)

DeborahK
DeborahK

Reputation: 60548

You have several options:

1) You could define a single object with properties for each parameter. Then your code would only need to assign/retrieve the one object.

let filters = {filter1:5,filter2:"Joe"};
this._router.navigate(['/products', {filter: JSON.stringify(filters)}]);

Where my hard-coded data could be replaced with user-entered values.

2) You could define a service with properties for each filter. The service is a singleton so one component could set the properties and another read the properties without having to go through route parameters.

Upvotes: 2

user4676340
user4676340

Reputation:

My take on this would be

this.route.params.subscribe((params: Params) => {
    for (let param in params) {
        this.params[param] = params[param];
    }
});

The for...in goes through all the keys, so that you can both set your key in the array AND get the key value in the params.

Upvotes: 0

Related Questions