使用Angular 2 Router的URL的自定义编码(使用+号代替空格) [英] Custom encoding for urls using Angular 2 Router (using a + sign in place of a space)

查看:91
本文介绍了使用Angular 2 Router的URL的自定义编码(使用+号代替空格)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2路由器更新搜索应用程序URL中的查询参数.我正在尝试用+号替换查询中的空格.但是,+号正在被编码.例如:

I am using an Angular 2 Router to update the query params in a URL for a search application. I am attempting to replace spaces in a query with + signs. However, + signs are getting encoded. For example:

this.router.navigatebyUrl('?q=one+two');

在URL中填充?q = one%2Btwo".

populates the URL with "?q=one%2Btwo".

在查看Angular 2的源代码时,路由器似乎将URL转换为UrlTree

In looking at the source code for Angular 2, it looks like the router converts the URL to a UrlTree which uses encodeURIComponent() to encode the url. Because of this, it is impossible to prevent the default encoding.

我当前的流程是,通过执行上述操作NavigationByUrl更改路线,然后使用以下命令监听更改:

My current process is that I change the route by doing navigateByUrl as seen above, and then listen for changes with:

this.routeSubscription = this.route.queryParams.subscribe((params: any) => {
  this.term = (params.q ? params.q : '');
});

有没有其他方法可以处理查询参数,从而允许我使用自己的网址编码策略?

Is there an alternate way to deal with query parameters that would allow me to use my own strategy for url encoding?

推荐答案

我能够找到解决问题的方法.您可以通过实现 UrlSerializer 类.

I was able to find a solution to my problem. You can make own custom url serializer by implementing the UrlSerializer class.

自定义网址序列化程序

创建一个自定义网址序列化器,如下所示:

Create a custom url serializer like this:

class CustomUrlSerializer implements UrlSerializer {
    parse(url: string): UrlTree {
        // Custom code here
    }

    serialize(tree: UrlTree): string {
        // Custom code here
    }
}

然后,您只需要提供CustomUrlSerializer来代替UrlSerializer,就可以在导入两个序列化器之后将其放置在AppModule提供程序数组中.

Then, you just need to provide the CustomUrlSerializer in place of the UrlSerializer, which you can place in the AppModule providers array after importing both serializers.

providers: [
    { provide: UrlSerializer, useClass: CustomUrlSerializer },
    ...
]

现在,当您调用router.navigate或router.navigateByUrl时,它将使用您的自定义序列化程序进行解析和序列化.

Now, when you call router.navigate or router.navigateByUrl, it will use your custom serializer for parsing and serializing.

使用+号作为空格

要将+号解析为空格:

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, '+');
}

DefaultUrlSerializer

这篇关于使用Angular 2 Router的URL的自定义编码(使用+号代替空格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆