我正在使用这个:
import { HttpParams } from '@angular/common/http';
let params = new HttpParams();
params.append('newOrdNum','123');
但这不起作用,我没有在URL中添加参数。有什么建议吗?我正在使用这个:
import { HttpParams } from '@angular/common/http';
let params = new HttpParams();
params.append('newOrdNum','123');
但这不起作用,我没有在URL中添加参数。有什么建议吗?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
});
}
}
如需更多信息,请查看 这本书 以及 Angular 的 Router API
skipLocationChanges
为 true
时,URL 不会显示出来,这是可以接受的。但我还没有弄清楚当它为 false
时会发生什么……你知道吗? - OmarskipLocationChanges
дёәfalse
ж—¶пјҢURLдјҡжҳҫзӨәеҸӮж•°гҖӮ - Isuru我不得不稍微调整Jota.Toledos的答案,以便它对我起作用,我必须删除extras对象的第二个和最后一个属性:
navigateToFoo(){
this._router.navigate([], {
queryParams: {
newOrdNum: '123'
},
queryParamsHandling: 'merge',
});
}
你应该编写
let params = new HttpParams();
params = params.append('newOrdNum','123');
this.router.navigate(['.'], { relativeTo: this.route, queryParams: { 'a': 'b' }, queryParamsHandling: 'merge', skipLocationChange: true});
路由器:Router 路由:ActivatedRoute
您应该使用Router
模块。请查看此文档:https://angular.io/guide/router
您需要导入以下模块:import { Router, ActivatedRoute, ParamMap } from '@angular/router';
Router
。 - Salim Ibrohimi// 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'
]);