Angular 5 URL 通过单击按钮进行路由并在 url 中保留查询字符串参数

Angular 5 URL routing with a button click and retain the querystring params in the url

我有一个 URL 是这样的

http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0

路由器模块根据这个知道显示

{ path: 'criminal/hearings', component: HearingsComponent, pathMatch: 'full'},

但现在我点击了一个按钮,我想在其中维护查询字符串。

按钮html

<button type="button" (click)="addHearing()" class="btn btn-primary">Add Hearing</button>

打字稿函数

addHearing(){
    this.router.navigate(['/cr/edithearings']) // how to include the querystring???
}

我想将现有的查询字符串添加到上面的按钮点击事件 然后在路由模块中,它与查询字符串

一起转到正确的路由
{ path: 'criminal/edithearings', component: HearingEditComponent, pathMatch: 'full'},

http://localhost:4200/criminal/edithearings?HOW_to_add?

addHearing(){
    this.router.navigate(['/cr/edithearings'], { queryParams: { key: value } })
}

navigate 有一个 queryParams 参数

如果您使用 HTML 模板导航,您可以使用 preserveQueryParams="true"

注意 preserveQueryParams 没有方括号。

例如:

<a [routerLink]="['/navigate-to']" preserveQueryParams="true">

代码内示例:

addHearing(){
    this.router.navigate(['somewhere'], { queryParamsHandling: "preserve" });
}