Angular:将查询参数附加到 URL

Angular: append query parameters to URL

我正在使用这个:

    import { HttpParams } from '@angular/common/http';
    let params = new HttpParams();
    params.append('newOrdNum','123');

但这不起作用,我没有在 url 中附加参数。有什么建议吗?

您应该使用 Router 模块。检查此文档:https://angular.io/guide/router

您需要导入这些模块: import { Router, ActivatedRoute, ParamMap } from '@angular/router';

这可以通过使用 Router class:

来存档

使用组件:

import { Router, ActivatedRoute } from '@angular/router';

@Component({})
export class FooComponent {
   constructor(
     private _route: ActivatedRoute,
     private _router: Router
   ){}

   navigateToFoo(){
     // changes the route without moving from the current view or
     // triggering a navigation event,
     this._router.navigate([], {
      relativeTo: this._route,
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
      // preserve the existing query params in the route
      skipLocationChange: true
      // do not trigger navigation
    });
   }
}

更多信息请查看this book and the angular Router API

我不得不稍微调整一下 Jota.Toledos 的答案,以便它对我有用,我不得不去掉第二个和最后一个 属性 的额外内容 - object:

   navigateToFoo(){
     this._router.navigate([], {
      queryParams: {
        newOrdNum: '123'
      },
      queryParamsHandling: 'merge',
    });
   }

您需要从 Angular 路由器获取查询参数的当前状态,修改这些属性(添加/删除参数),然后使用路由器重新分配它:

// 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 });


您甚至可以更进一步,构建一个效用函数来执行此操作:

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 });
}

然后您只需使用将参数映射到新值的对象调用 handleUrlParameters,或者调用要删除的参数名称数组。

确保在传递查询参数值时不应未定义。

      this.router.navigate([yourRoute,
         queryParams : 
              {
                key : (yourValue ? yourValue : '')
              },
         queryParamsHandling: 'merge'
            ]);
      

你应该写

let params = new HttpParams();
params = params.append('newOrdNum','123');
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'a': 'b' }, queryParamsHandling: 'merge', skipLocationChange: true});

路由器:路由器 路线:ActivatedRoute