[英]How to update matrix parameters in Angular2
在 Angular2 中,有沒有辦法更新矩陣參數,但導航到同一個組件? 基本上想從如下所示的 url 輕松轉換:
/search;term=paris;pageSize=24;currentPage=1;someFilter=value;
同樣的事情,但在分頁時更新 currentPage :
/search;term=paris;pageSize=24;currentPage=2;someFilter=value;
使用router.navigate
似乎不是最好的選擇,因為我必須編寫大量自己的邏輯來重新構建 url 以供navigate
使用(重新構建已經存在的東西)。
對於踢腿和傻笑,我確實嘗試過
this._router.navigate([this._router.url, {currentPage: this.pagination.currentPage}]);
但是(如您所料),路由器對當前 url 上有矩陣參數這一事實很愚蠢,因此結果並不漂亮。
編輯:還應該提到可能有任意數量的矩陣參數的附加鍵/值對,因此對任何路由進行硬編碼都是不可能的
編輯:我從那以后嘗試使用preserveQueryParams: true
像:
this._router.navigate(["..", {currentPage: this.pagination.currentPage}], {preserveQueryParams: true});
為了獲得易於使用/可轉移的解決方案,但這並沒有將矩陣參數保留在路線上。
更新:我已經實現了我自己的邏輯來獲得所需的行為,所以這里是解決方案的代碼片段:
let currentParamsArr: Params = this.route.snapshot.params;
let currentParamsObj: any = { };
for (let param in currentParamsArr) {
currentParamsObj[param] = currentParamsArr[param];
}
currentParamsObj.currentPage = +pageNum; //typecasting shortcut
this._router.navigate([currentParamsObj], { relativeTo: this.route });
這段代碼循環遍歷參數(就像它們在快照中一樣),並從中創建一個對象,然后添加/編輯我想要更新的參數,然后導航到“新”路由
但是,這並不漂亮,因為我將在程序的許多地方基本上具有相同的邏輯,或者必須對 Router 進行修改或提供一些其他通用方法。
最終對我來說效果很好的方法是這樣的:
let route: ActivatedRoute;
const newUrl = router.createUrlTree([
merge({'a': 123}, route.snapshot.params)
], {relativeTo: route});
通過使用merge,你可以添加、更新和減去url參數,然后使用router.navigateByUrl(newUrl)
來執行。
add: merge({newParam: 111}, route.snapshot.params)
update: merge({param: 111}, route.snapshot.params)
subtract: merge({param: null}, route.snapshot.params)
希望其他人覺得這和我一樣有用。
另一個使用 Object.assign 而不是 merge 的例子:
let route = this.route; // The imported ActivatedRoute
let currentParamsObj: Params = Object.assign({}, route.params);
let newParam = {};
newParam[key] = value;
let newUrl = this._router.createUrlTree([
Object.assign(currentParamsObj, newParam)
], {relativeTo: this.route });
this._router.navigateByUrl(newUrl);
你有沒有試過使用類似的東西
this._router.navigateByUrl('/search;term='+this.term+';pageSize='+this.pageSize+';currentPage='+this.currentPage+';someFilter='+this.someFilter;
就我而言,我有一個父子路由器,我需要修改父級上的參數: /my-parent;x=1;y=2/my-child
使用@Corbfon 的解決方案,我能夠像這樣修改父路由:
// modify the context params in the PARENT route
const newParam = {'z': '3'};
const parentParams: Params = Object.assign({ ...this.activatedRoute.parent.snapshot.params }, newParam);
// note: this approach doesn't preserve params on the child route (but there aren't any in my case)
const currentChildPath = this.activatedRoute.routeConfig.path;
// notice it's relativeTo the parent route
const newUrl = this.router.createUrlTree([parentParams, currentChildPath],
{relativeTo: this.activatedRoute.parent});
this.router.navigateByUrl(newUrl);
希望這對其他人有幫助。
PS 不要忘記在ActivatedRoute
上使用.snapshot.params
而不是.params
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.