Angular navigate to url by replacing an existing p

2020-03-08 06:32发布

问题:

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/2016

url/customers/2017

OR

url/customers/some-other-page/2015

url/customers/some-other-page/2016

url/customers/some-other-page/2017

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.

We tried:

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

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

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

The third time:

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

and so on...

Question:

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

回答1:

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'));
    . . .
}

NOTE: From the docs:

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

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

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



标签: angular