How to avoid URL Encoding
with navigate
? Currently, I am navigating url as below and It is encoding url like /
as %2F
. I want to avoid it so is there anyway to do it ?
this.router.navigate(['/comp', { type: this.Type }]);
Asked
Active
Viewed 1,076 times
0

Jeeten Parmar
- 5,568
- 15
- 62
- 111
1 Answers
0
Angular2 by default uses encodeURIComponent() to encode queryParams in URL, you can avoid it by writing custom URL serializer and override default functionality.
In my case, I wanted to avoid Angular2 to avoid replacing comma(,) by (%2). I was passing Query as lang=en-us,en-uk where it was getting converted to lang=en-us%2en-uk.
Here how I worked it out:
CustomUrlSerializer.ts
import {UrlSerializer, UrlTree, DefaultUrlSerializer} from '@angular/router';
export class CustomUrlSerializer implements UrlSerializer {
parse(url: any): UrlTree {
let dus = new DefaultUrlSerializer();
return dus.parse(url);
}
serialize(tree: UrlTree): any {
let dus = new DefaultUrlSerializer(),
path = dus.serialize(tree);
// use your regex to replace as per your requirement.
return path.replace(/%2/g,',');
}
}
Add below line to your main appModule.ts
import {UrlSerializer} from '@angular/router';
import {CustomUrlSerializer} from './CustomUrlSerializer';
@NgModule({
providers: [{ provide: UrlSerializer, useClass: CustomUrlSerializer }]
})
This won't break your default functionality and take cares of URL as per your need.

jigar gala
- 1,600
- 12
- 20