Angular: append query parameters to URL

前端 未结 6 1121
萌比男神i
萌比男神i 2020-12-28 14:43

Im using this:

    import { HttpParams } from \'@angular/common/http\';
    let params = new HttpParams();
    params.a         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 15:08

    You'll want to take the current state of the query parameters from the Angular Router, modify those props (add / delete parameters), then reassign it using the Router:

    // Make sure to import and define the Angular Router and current Route in your constructor
    constructor(
      private router: Router,
      private route: ActivatedRoute
    ) {}
    
    ...
    ...
    ...
    
    // Take current queryParameters from the activated route snapshot
    const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 
    
    // Need to delete a parameter ?
    delete urlParameters.parameterName;
    
    // Need to add or updated a parameter ?
    urlParameters.parameterName = newValue;
    
    // Update the URL with the Angular Router with your new parameters
    this.router.navigate([], { relativeTo: this.route, queryParams: urlParameters });
    
    
    

    You could even go further and build a utility function to do this:

    handleUrlParameters(paramsToAdd: {param: string}[], paramsToDelete?: string[]) {
      const urlParameters = Object.assign({}, this.route.snapshot.queryParams); 
    
      paramsToDelete.forEach(param => delete urlParameters[param]);
    
      Object.keys(paramsToAdd).forEach(param => urlParameters[param] = paramsToAdd[param]);
    
      this.router.navigate([], { relativeTo: this.route, queryParams: urlParameters });
    }
    

    And then you simply call handleUrlParameters with an object mapping a parameter to new values, or an array of parameter names to delete.

提交回复
热议问题