Reputation: 12373
I need to customize how my URLs are encoded when calling the navigate
method on the router.
I know I need to implement my own version of UrlSerializer
and write a custom serialize
method. My problem is really that the only method I wish to change is the encode
method in url_tree
.
export function encode(s) {
return encodeURIComponent(s);
}
https://github.com/angular/angular/blob/master/modules/@angular/router/src/url_tree.ts#L344
In order to do this I need to copy + paste all the following methods from url_tree
into my CustomSerializer
because they are not exported:
serialize
serializeQueryParams
Pair
pairs
serializeSegment
encode
I've looked at this answer but it doesn't quite solve my problem as I want all the default behaviour except for the encode
method.
Am I missing something here or is there a better way to solve this issue?
Upvotes: 0
Views: 4016
Reputation: 1650
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 (%2C). I was passing Query as lang=en-us,en-uk where it was getting converted to lang=en-us%2Cen-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(/%2C/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.
Upvotes: 6