角度:以编程方式更新url时queryParams不起作用

时间:2019-05-02 15:36:08

标签: angular routes queryparam

当我以编程方式更新网址的查询参数时,如下所示:

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

,然后尝试使用ActivatedRoute这样的服务获取此参数:

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

我得到这个结果:

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

有人可以解释这种行为吗?预先感谢。

我的实际代码:

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

我创建的服务:

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 个答案:

答案 0 :(得分:0)

该值未更新,因为路由的快照是在组件的首次加载时获取的。该值仅在首次加载组件时计算得出,除非重新加载页面,否则不会更改。

幸运的是,您可以直接订阅查询参数,这将对您的用例有所帮助:

this.activeRoute.queryParams.subscribe(queryParams => {
        // Do something with the query params
    });