在Angular中处理多个查询参数

时间:2019-07-16 18:25:55

标签: angular

我正在使用Angular Material选项卡,并且我想使用查询参数将选定的选项卡保存在URL中(我只有2个选项卡)。 另外,当我在选项卡1上时,我必须具有2个查询参数,一个用于所选选项卡,另一个用于另一个所选值(inspectionChecklistId)。 我的问题是,当我在第二个选项卡上并且尝试更新现有参数(selectedTab)并同时添加新参数(inspectionChecklistId)时,因为第一个参数未更新。 我不得不提到,我正在使用一种更新查询参数的方法。

我正在使用这种方法来更新查询参数:

updateQueryParams(name: string, value: number){
  this.router.navigate([], {
    relativeTo: this.activatedRoute,
    queryParams: {
      [name]: value
    },
    queryParamsHandling: "merge"
 });
}

然后我尝试更新查询参数: 在构造函数中,我仅使用选定的tab参数调用该方法一次:

constructor(private router: Router, private activatedRoute: ActivatedRouter) {
   this.updateQueryParams('selectedTab', 0);
}

在每次更改选项卡时都会调用的方法中,我做了这样的事情:

onSelectedIndexChanged(index: number){
  this.updateQueryParams('selectedTab', index);

  if(index === 1) {
    this.updateQueryParams('inspectionChecklistId', -1);
  } else {
    this.updateQueryParams('inspectionChecklistId', null);
  }
}

我还尝试过这样更改updateQueryParams:

updateQueryParams(...queryParams) {
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams: {
        ...queryParams
      },
      queryParamsHandling: "merge"
    });
}

并使用如下方法:

  onSelectedIndexChanged(index: number) {
    if (index === 1) {
      this.updateQueryParams(
        { name: "selectedTab", value: index },
        { name: "inspectionChecklistId", value: -1 }
      );
    } else {
      this.updateQueryParams({ name: "inspectionChecklistId", value: null });
    }
  }

但是使用传播类型,像我一样添加整个queryParams数组是错误的,而且我不知道如何分别添加每个元素。

这就是我想要的:

-tab 0 is selected (the first one) => localhost:4200/?selectedTab=0
-tab 1 is selected (the second one) => localhost:4200/?selectedTab=1&inspectionChecklistId=-1

但是现在,selectedTab并没有改变。

1 个答案:

答案 0 :(得分:0)

您不需要使用传播类型,只需传递类型为Params的参数:

updateQueryParams(queryParams) {
    this.router.navigate([], {
      relativeTo: this.activatedRoute,
      queryParams,
      queryParamsHandling: 'merge'
    });
  }

在构造函数中,传递params对象:

constructor(private router: Router, private activatedRoute: ActivatedRoute) {
  this.updateQueryParams({selectedTab: 0});
}

当选项卡更改时,仅调用一次函数,并传递两个查询参数:

onSelectedIndexChanged(index: number) {
  const inspectionChecklistId = index === 1 ? -1 : null;
  this.updateQueryParams(
    {
      selectedTab: index,
      inspectionChecklistId
    }
  );
}
相关问题