Zarepheth
Zarepheth

Reputation: 2593

How to create/update a ParamMap in Angular 5?

In Angular 5, the Router/ParamMap object is immutable. It can be retrieved from the route and used in a component. However, I have a use case for which modifying the ParamMap would be convenient (and it worked fine with Angular 4).

Previously, I used the convertToParamMap function to convert an Object to a ParamMap. Since updating to Angular 5, the resulting ParamMap object's private params member loses its prototype and generates an error when I call the resulting ParamMap's .get(key) method.

const params = this.routeParams.keys.reduce(
    (pv: Params, cv) => {
        pv[cv] = this.routeParams.get(cv); // <- Error on second call
        return pv;
    },
    Object.create(null) as Params
);
params["changedKey"] = newValue;
this.routeParams= convertToParamMap(params);

this.routeParams is initially populated from a call to the ActivatedRoute instance's queryParamMap method and simply setting my component's routeParams member to the returned ParamMap instance.

On my first pass through the code above, everything works fine. On the second pass, after I've updated the routeParams member with the convertToParamMap function, I receive this error:

Object doesn't support property or method 'hasOwnProperty'

Via the debugger, the .get(cv) call is internally calling the .has(cv) method, which then calls this.params.hasOwnProperty(name) (this = the ParamMap object and name = cv). I'm thinking this is a bug in Angular 5, but I'm looking for an alternative or workaround until it gets fixed.

Any suggestions?

Upvotes: 0

Views: 3842

Answers (1)

Zarepheth
Zarepheth

Reputation: 2593

I'm not so sure this is the best way to go, but it's working for me.

Instead of Object.create(null) as Params, I'm creating the initial value like this:

const initialValue = Object.create((this.routeParams as any).params.__proto__);

This creates an "empty" object whose prototype matches that of the original, private params object, so after calling the convertToParamMap function, the resulting ParamMap instance's internal params object has the hasOwnProperty(name) method.

Personally, I don't like calling private members from outside the object which contains them, but this works, so I'll be using it until a better option comes along.

Upvotes: 1

Related Questions