Angular:将查询参数附加到URL

Non*_*one 15 query-parameters angular2-routing angular2-router angular

我用这个:

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

但这不起作用,我不会在网址中附加param.有什么建议吗?

Jot*_*edo 41

这可以通过使用Router类来存档:

使用组件:

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
    });
   }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看本书和角度路由器API

  • 当 `skipLocationChanges` 为 `true` 时,url 不会显示它。这很好。但我还没有弄清楚当它是“false”时会发生什么……你知道吗? (4认同)
  • 当“skipLocationChanges”为“false”时,URL 显示参数 (2认同)

Jan*_*gen 8

我必须调整Jota.Toledos一点回答,以便它对我有用,我必须取出extras的第二个和最后一个属性-object:

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

  • 当您的查询参数更改时,这也会反映在网址中吗? (2认同)

小智 5

你应该写

let params = new HttpParams();
params = params.append('newOrdNum','123');
Run Code Online (Sandbox Code Playgroud)