我正在使用Angular 2路由器更新搜索应用程序URL中的查询参数。我正在尝试用+号替换查询中的空格。但是,+号正在被编码。例如:
this.router.navigatebyUrl('?q=one+two');
用“?q = one%2Btwo”填充URL。
在查看Angular 2的源代码时,路由器似乎将URL转换为UrlTree ,后者使用encodeURIComponent()对url进行编码。因此,不可能阻止默认编码。
我当前的过程是,通过执行上图所示的navigationByUrl来更改路线,然后使用以下命令监听更改:
this.routeSubscription = this.route.queryParams.subscribe((params: any) => {
this.term = (params.q ? params.q : '');
});
有没有其他方法可以处理查询参数,使我可以使用自己的网址编码策略?
我能够找到解决问题的方法。您可以通过实现UrlSerializer类来制作自己的自定义url序列化程序。
自定义网址序列化器
创建一个自定义网址序列化器,如下所示:
class CustomUrlSerializer implements UrlSerializer {
parse(url: string): UrlTree {
// Custom code here
}
serialize(tree: UrlTree): string {
// Custom code here
}
}
然后,您只需要提供CustomUrlSerializer来代替UrlSerializer,就可以在导入两个序列化器之后将其放置在AppModule提供程序数组中。
providers: [
{ provide: UrlSerializer, useClass: CustomUrlSerializer },
...
]
现在,当您调用router.navigate或router.navigateByUrl时,它将使用您的自定义序列化程序进行解析和序列化。
使用+号作为空格
要将+号解析为空格:
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)
}
对于序列化:
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, '+');
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句