修改Angular路由器导航方法的默认URL编码 [英] Modifying the default URL encoding for Angular's router navigate method
问题描述
在路由器上调用navigate
方法时,我需要自定义URL的编码方式.
I need to customize how my URLs are encoded when calling the navigate
method on the router.
我知道我需要实现自己的UrlSerializer
版本并编写自定义的serialize
方法.我的问题确实是,我唯一想更改的方法是url_tree
中的encode
方法.
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
为此,我需要将以下所有方法从url_tree
复制并粘贴到我的CustomSerializer
中,因为它们不会被导出:
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
我已经看过这个 answer ,但是它并不能完全解决我的问题,因为我想要所有默认行为除了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?
推荐答案
默认情况下,Angular2使用encodeURIComponent()对URL中的queryParams进行编码,您可以通过编写自定义URL序列化程序并覆盖默认功能来避免使用它.
Angular2 by default uses encodeURIComponent() to encode queryParams in URL, you can avoid it by writing custom URL serializer and override default functionality.
就我而言,我想避免Angular2,以避免用(%2C)替换逗号(,).我将Query传递为lang = en-us,en-uk,并将其转换为lang = en-us%2Cen-uk.
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.
这是我的解决方法:
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,',');
}
}
将以下行添加到主 appModule.ts
import {UrlSerializer} from '@angular/router';
import {CustomUrlSerializer} from './CustomUrlSerializer';
@NgModule({
providers: [{ provide: UrlSerializer, useClass: CustomUrlSerializer }]
})
这不会破坏您的默认功能,并会根据您的需要处理URL.
This won't break your default functionality and take cares of URL as per your need.
这篇关于修改Angular路由器导航方法的默认URL编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!