Custom URL encoding using Angular 2 Router (using + sign instead of space)

I am using Angular 2 Router to update request parameters in the url for the search application. I am trying to replace spaces in the request with a +. However, the + signs are encoded. For example:

this.router.navigatebyUrl('?q=one+two'); 

populates the URL with "? q = one% 2Btwo".

When looking at the source code for Angular 2, it looks like the router converts the URL to UrlTree which uses encodeURIComponent () to encode the URL . Because of this, it is not possible to prevent the default encoding.

My current process is that I am changing the route by doing navigateByUrl as shown above and then listening to the changes with:

 this.routeSubscription = this.route.queryParams.subscribe((params: any) => { this.term = (params.q ? params.q : ''); }); 

Is there an alternative way to handle request parameters that would allow me to use my own URL encoding strategy?

+6
angular angular2-routing
source share
1 answer

I managed to find a solution to my problem. You can create your own custom URL serializer by implementing the UrlSerializer class.

Custom URL serializer

Create your own URL serializer as follows:

 class CustomUrlSerializer implements UrlSerializer { parse(url: string): UrlTree { // Custom code here } serialize(tree: UrlTree): string { // Custom code here } } 

Then you just need to provide a CustomUrlSerializer instead of an UrlSerializer, which can be placed in the AppModule providers array after importing both serializers.

 providers: [ { provide: UrlSerializer, useClass: CustomUrlSerializer }, ... ] 

Now when you call router.navigate or router.navigateByUrl, it will use your own serializer for parsing and serializing.

Using + characters as spaces

To parse + signs as spaces:

 parse(url: string): UrlTree { // Change plus signs to encoded spaces url = url.replace(/\+/g, '%20'); // Use the default serializer that you can import to just do the // default parsing now that you have fixed the url. return this.defaultUrlSerializer.parse(url) } 

And for serialization:

 serialize(tree: UrlTree): string { // Use the default serializer to create a url and replace any spaces with + signs return this.defaultSerializer.serialize(tree).replace(/%20/g, '+'); } 

DefaultUrlSerializer

+13
source share

All Articles