Angular: How to update queryParams without changing route

后端 未结 8 557
日久生厌
日久生厌 2020-12-07 09:01

I am trying to update (add, remove) queryParams from a component. In angularJS, it used to be possible thanks to :

$location.search(\'f\', \'filters[]\'); //         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 09:08

    The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.

    My solution was to use lotation.go:

    import { Component } from "@angular/core";
    import { Location } from "@angular/common";
    import { HttpParams } from "@angular/common/http";
    
    export class whateverComponent {
      constructor(private readonly location: Location, private readonly router: Router) {}
    
      addQueryString() {
        const params = new HttpParams();
        params.append("param1", "value1");
        params.append("param2", "value2");
        this.location.go(this.router.url.split("?")[0], params.toString());
      }
    }
    

    I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.

    and the this._router.url.split("?")[0], is to remove all previous query string from current url.

提交回复
热议问题