gpt4 book ai didi

Angular :替换 url 中的段

转载 作者:行者123 更新时间:2023-12-03 19:27:00 30 4
gpt4 key购买 nike

此问题与 SO 上的以下现有问题重复:

Angular router: how to replace param?

Generically replace Angular 2 route parameter and navigate

Angular 6 router - replace some of the parameters of the current route

Angular2-router: How to only change a parameter of a route?

How can I change a specific, internal route parameter in Angular2

这些问题的答案都没有完全解决替换 url 中的一个段的问题,因此我再次提出这个问题。

总结我的情况:

这些是我项目中的一些路线(我自己没有想出这个,所以请多多包涵)

/:customer/static/part/of/url
/:customer/other/static/stuff
/something/for/the/:customer
/something/without/anything
/other/stuff/:customer/might/need

参数 ":customer"出现在 url 的不同位置。我的问题是这个客户 ID 可能会在后端更改,而无需前端的任何操作。我正在监听后端的变化,并且必须相应地调整 url,以防客户 ID 发生变化。

简单的 string.replace 行不通,因为从技术上讲,客户 ID 可能实际上和字面上是“静态”或“其他”。

问题:

如何分析当前 url (ActivatedRoute?) 以仅替换与客户 id 相关的 url 的一部分(paramMap 具有“customer”),同时保持 url 的其余部分原样?

最佳答案

要读取字符串中的文本模式,我建议使用正则表达式。

例如,如果您的客户 ID 类似于“123456”,则正则表达式可以是/\d{6}/(此处的斜杠是为了描述正则表达式模式,而不是 url 模式):

let url = '/something/for/the/123456' // 123456 denotes :customer here
let pattern = /\d{6}/;

let customerId = url.match(pattern);

注意定义仅与 URL 中的客户 ID 匹配的模式。

您可以在此处找到有关 JavaScript 正则表达式的更多信息: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/RegExp

我差点忘了,您可以使用 String.replace() 函数替换字符串中的模式:
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/replace

关于 Angular :替换 url 中的段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935128/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com