angular 2禁用url编码 [英] angular 2 disable url encoding
问题描述
我想禁用网址编码。
当我在下方使用时。
this.router.navigate(['/profile', { tags: 'one,two' }]);
网址是这样的
http://localhost:4200/profile;tags=one%2Ctwo
我希望它非常像下面
http://localhost:4200/profile;tags=one,two
有没有办法禁用网址编码?
Is there a way to disable the url encoding?
推荐答案
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避免用(%2)替换逗号(,)。我正在传递Query为lang = en-us,en-uk,它被转换为lang = en-us%2en-uk。
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.
这是我如何工作的out:
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,',');
}
}
将以下行添加到主appModule.ts
Add below line to your main 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 2禁用url编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!