4

I'm using Angular 7. I'm trying to navigate to one of the defined urls, passing query parameters:

this.router.navigate(['/someurl'], {queryParams: {r: id}});

as a result of this call, application navigates to localhost:4200/someurl?r=25. This looks good so far, but after I refresh page the url changes to localhost:4200/someurl%3Fr%3D25 and that leads to this error in console:

Error: Cannot match any routes. URL Segment: 'someurl%3Fr%3D25'

How can I force my application (or browser) not to substitute special symbols ('?' and '=' in my example)? I know that it is a cause of my error, but I don't know how to prevent it.

dim0_0n
  • 2,404
  • 5
  • 27
  • 46
  • Out of curiosity, why are you using queryParams like that instead of setting up your route as `{ path: 'someurl/:id', component: ComponentNameHere }` and doing `this.router.navigate(['/someurl/25'])`? – yanbu Jul 19 '19 at 22:42
  • This example shows only one query parameter, but the real app has many of them. Some of them can be undefined (absent in url path). It is cleaner to use query parameters in that case. – dim0_0n Jul 19 '19 at 22:47
  • Is this a search feature? It might be better to store the object in a service and then pass it to your component. – yanbu Jul 20 '19 at 23:35
  • @yanbu, one advantage of URL query params is you can share the url to other or when you go back (by browser back button) all query params are there. If you store the query params in service, how can you store the history of params (if user go back many times)? – trungkmy Jun 18 '20 at 05:15

1 Answers1

0

In angular query parameters are shared between all routes. By discussion in the comments, I can suggest you should use matrix parameters in your case, which are route specific. Just pass the object with params directly to navigate method:

this.router.navigate(['/someurl'], {r: id});
Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123
  • My case is that after I refresh page, special symbols turn into encoded string, which occurs even if I use matrix parameters. – dim0_0n Jul 20 '19 at 08:42