Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing strings as route parameters in Angular without encoding

I am trying to pass a string using this code:

  this.router.navigate(['/systems', params.toString()]);

The route parameter is then appended to a URL for an API call. The params.toString() is change_user=2258. When it is sent through the browser however, it is changed to change_user%3D2558 on the URL. When I use the developer tools to see what was sent to the API, it was changed to NaN.
How do I pass a string through a router, so that I can directly append it to my API string?

Edit: The variable params is of type URLSearchParams(). This is how I'm trying to extract the parameter:

this.route.paramMap.switchMap((params: ParamMap) => 
this.httpService.getSites(+params.get('params')))
.subscribe(sites => this.sites = sites);
like image 632
ecain Avatar asked Jul 21 '17 22:07

ecain


People also ask

Can we pass data in router outlet in Angular?

There are various ways by which we can pass data from one component to another. Angular 7.2. 0 introduced a new way to pass data using State Object while navigating between routed components.

Where do you set the route parameter value in Angular?

First, add links to the two components. Assign the anchor tag that you want to add the route to the routerLink attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include <router-outlet> .


2 Answers

So here was how I fixed it:

All I had to simply do was take out the + in the +params.get() call. Apparently what that does is try and convert it to a number. Now I am able to pass in my params.toString() directly.

like image 86
ecain Avatar answered Oct 25 '22 02:10

ecain


Add a route definition with a parameter as described here in the Angular 2 routing documentation

{ path: 'hero/:id', component: HeroDetailComponent }

Option 1

You then will be able to navigate to the route with

let id = 2258;
this.router.navigate(['/hero', id]);

And use the ActivatedRoute in @angular/router to extract the parameters as described here in the documentation

let id = this.route.snapshot.paramMap.get('id');

Option 2

Use the router.navigateByUrl() methods (documentation here)

router.navigateByUrl('/hero/2258');
like image 33
0mpurdy Avatar answered Oct 25 '22 01:10

0mpurdy