角度通过替换现有参数导航到url [英] Angular navigate to url by replacing an existing parameter

查看:53
本文介绍了角度通过替换现有参数导航到url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的 Angular 应用中,我们有一个Dropdown组件,其中填充了年份.

In our Angular App we have a DropDown component which is populated with years.

选择一年后,我们需要更改路由器网址,例如:

Once we select an year, we need to change the router url, to be something like:

url/customers/ 2015

url/customers/2015

url/customers/ 2016

url/customers/2016

url/customers/ 2017

url/customers/2017

OR

url/customers/some-other-page/ 2015

url/customers/some-other-page/2015

url/customers/some-other-page/ 2016

url/customers/some-other-page/2016

url/customers/some-other-page/ 2017

url/customers/some-other-page/2017

这可行,但是我们将下拉列表的change事件委托给需要它的组件.很好!

This works, but we delegate the change event of the dropdown to the components that need it. That is fine!

但我们认为,如果该组件自行改变路线,则会使我们的生活更轻松.

BUT we thoughtit would make our life easier, if the component makes the route change by itself.

我们尝试过:

  public onChange(year): void {   
    this.router.([this.router.url, year]);
  }

这仅在第一次使用时有效,第二次,URL如下所示:

This works only in the first time, the second time the url looks like this:

URL/客户/其他页面/ 2017/2018

url/customers/some-other-page/2017/2018

第三次:

URL/客户/其他页面/ 2017/2018/2019

url/customers/some-other-page/2017/2018/2019

以此类推...

问题:

那么,如何获取路由器的参数并将其替换为当前参数?

So, how do I get the parameter of my router and replace it with the current paremeter?

推荐答案

以下是有关使用查询参数的一些信息:

Here is some info on using query parameters:

然后您可以使用如下语法读取查询参数:

You can then read the query parameters using syntax like this:

ngOnInit(): void {
    this.listFilter = this.route.snapshot.queryParamMap.get('filterBy') || '';
    this.showImage = this.route.snapshot.queryParamMap.get('showImage') === 'true';
    . . .
}

或者,如果您希望在查询参数更改时收到通知,可以执行以下操作:

Or if you want to be notified when the query parameters change, you can do something like this:

ngOnInit(): void {
    this.route.queryParamMap.subscribe(params => this.filterBy = params.get('filterBy'));
    . . .
}

注意:来自文档:

两个较旧的属性仍然可用.他们能力不如 不推荐使用它们的替代品,将来可能不推荐使用 角度版本.

Two older properties are still available. They are less capable than their replacements, discouraged, and may be deprecated in a future Angular version.

params —包含必需和可选的Observable 特定于路线的参数.请改用paramMap.

params — An Observable that contains the required and optional parameters specific to the route. Use paramMap instead.

queryParams —包含查询参数的Observable 适用于所有路线.改用queryParamMap.

queryParams — An Observable that contains the query parameters available to all routes. Use queryParamMap instead.

这篇关于角度通过替换现有参数导航到url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆