1

When I update the url's query params programmtically like so:

window.history.pushState({}, '', 'http://localhost:4200/#/some/url?param=value');

and then try to get this param using ActivatedRoute service like this:

let params = this._activatedRoute.snapshot.queryParams;
console.log(params);

I get this result:

{param: ''} // should be {param: 'value'}

can someone explain this behavior ? thanks in advance.

My actual code:

let url = LocationManager.addParam({key: 'param', value: 'value'});
window.history.pushState({}, '', url);
this._activatedRoute.queryParams.subscribe(queryParams => {
     console.log({queryParams});
});

a service I have created:

export class LocationManager{

    /**
     * Get value of param
     * @param param 
     * @returns value
     */
    static param(param){
        return this.params()[param];
    }

    /**
     * add param to url
     * @param param 
     * @returns url
     */
    static addParam(param: {key: string, value: string}){
        let params = this.params();
        params[param.key] = param.value;
        return this.buildURL(params);
    }

    /**
     * Return query params of url
     */
    static params(){
        let params = {};
        let url = window.location.href;

        if(url.includes('?')){
            let paramsString = url.split('?')[1];
            let p = paramsString.split('&');

            p.forEach((item) => {
                let kv = item.split('=');
                params[kv[0]] = kv[1];
            });
        }

        return params;
    }

    /**
     * Build url from query params
     * @param params 
     */
    static buildURL(params: {}){
        let array = [];
        for(let key in params){
            array.push(`${key}=${params[key]}`);
        }
        let paramsString = array.join('&');
        let url = window.location.href;
        let splietdURL = url.split('?');
        return `${splietdURL[0]}?${paramsString}`;
    }
}
1

1 Answer 1

2

The value isn't updating, because the snapshot of the route is taken at the first load of the component. The value will only be calculated for the first load of the component and won’t change unless you reload the page.

Luckily you can subscribe to the query params directly and that should help your use case:

this.activeRoute.queryParams.subscribe(queryParams => {
        // Do something with the query params
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Would you please share your actual component code instead of the little snippets?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.