简体   繁体   English

在Angular4 routerLink中转义URL

[英]Escaping of URLs in Angular4 routerLink

With Angular4 I can use the following syntax to link to a component: 使用Angular4,我可以使用以下语法链接到组件:

<a routerLink="MYLINK">link</a>

However the syntax of MYLINK is unclear to me. 但是,我不清楚MYLINK的语法。 Is it a path according to RFC 3986, ie does it have to follow URL escaping rules? 它是符合RFC 3986的路径,即是否必须遵循URL转义规则? Or is it a concatenation of unescaped path segments? 还是未转义的路径段的串联?

For example, would I write 例如,我会写

<a routerLink="/root/my%20page">link</a>

or 要么

<a routerLink="/root/my page">link</a>

Is this documented anywhere in Angular? 这在Angular中有记录吗?

My expectation would be that when passing a path, the path would have to be URL encoded. 我的期望是,当传递路径时,该路径必须是URL编码的。 When passing an array of segments, the segments would not be URL encoded. 当传递一个段数组时,这些段将不会进行URL编码。

Crea un archivo CustomUrlSerializer.ts 创建档案CustomUrlSerializer.ts

import {UrlSerializer, UrlTree, DefaultUrlSerializer} from '@angular/router'; 从'@ angular / router'导入{UrlSerializer,UrlTree,DefaultUrlSerializer};

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(/%20/g,' ');
    }
}

` `

import en tu app.module.ts 导入en app.module.ts

providers: [{ provide: UrlSerializer, useClass: CustomUrlSerializer }], 提供者:[{提供:UrlSerializer,useClass:CustomUrlSerializer}],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM