如何在Angular2中更新矩阵参数

Cor*_*fon 7 javascript angular-ui-router angular

在Angular2中,有没有办法更新矩阵参数,但导航到同一个组件?基本上想要从一个看起来像这样的网址轻松过渡:

/search;term=paris;pageSize=24;currentPage=1;someFilter=value;

同样的事情,但在分页时更新currentPage:

/search;term=paris;pageSize=24;currentPage=2;someFilter=value;

使用router.navigate似乎并不是最佳选择,因为我必须编写大量自己的逻辑来重新构建用于navigate使用的URL (重新构建已经存在的东西).

对于踢腿和咯咯笑,我确实尝试过

this._router.navigate([this._router.url, {currentPage: this.pagination.currentPage}]);

但是(正如你所料),路由器对于当前网址上有矩阵参数这一事实是愚蠢的,所以结果不是很好.

编辑:还应该提到可能有任意数量的矩阵参数的附加键/值对,因此硬编码任何路由都是不可能的

编辑:我以后尝试使用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 });
Run Code Online (Sandbox Code Playgroud)

这段代码循环遍历参数(因为它们位于快照中),并从中创建一个对象,然后添加/编辑我想要更新的参数,然后导航到"新"路径

但是,这并不漂亮,因为我在程序的许多地方基本上都有相同的逻辑,或者必须对路由器进行修改或提供其他一些通用方法.

Cor*_*fon 5

最终对我有效的方法是:

let route: ActivatedRoute;
const newUrl = router.createUrlTree([
  merge({'a': 123}, route.snapshot.params)
], {relativeTo: route});
Run Code Online (Sandbox Code Playgroud)

通过使用合并,您可以添加,更新和减去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)
Run Code Online (Sandbox Code Playgroud)

希望其他人能像我一样有用。

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