修改Angular路由器导航方法的默认URL编码 [英] Modifying the default URL encoding for Angular's router navigate method

查看:155
本文介绍了修改Angular路由器导航方法的默认URL编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在路由器上调用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屋!

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