gpt4 book ai didi

Angular 路线 : URL like/my/:parameter/path

转载 作者:行者123 更新时间:2023-12-05 08:32:07 25 4
gpt4 key购买 nike

我正在尝试设置一个类似 'user/:id/edit' 的 URL,但是当我使用 [routerLink]="['user/:id/edit', 1 ]" 它生成 /user/:id/edit/1

如果我使用 [routerLink]="['user/:id/edit', {id: 1}]" 它会生成 /user/:id/edit;id= 1

有没有办法在不使用字符串插值的情况下将输出作为 /users/1/edit

最佳答案

我相信你的这个问题是another question of yours.的延伸在这里,您的要求是获得一个根据您要传递的参数正确翻译的数组。我的意思是:

假设我们有一个路由配置为

const routes: Routes = [
{path: "first/:id1/second/:id2", component: HelloComponent}
]

[routerLink] 中使用它时,您需要输入属性如下:['first', 'param1', 'second', 'param2' ]。不是:['first/param1/second/param2']。如果你这样做,那么即使你将被路由到所需的路径,你的 ActivatedRoute 也不会包含任何参数(以防你需要从路由器获取参数)。

现在您的任务是为 routerLinks 创建这样的数组。

让我们创建一个 Pipe 来执行此操作并且性能高效。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'routerArray'
})
export class RouterArrayPipe implements PipeTransform {
transform(routerPath: string, params: string | number[]): string | number[] {
// regex to find all the param placeholders in the route path
let regex = /(\/:[a-zA-Z0-9]*\/?)/g;
// will be returned as output
let routerArray = [];
// contains the output of regex.exec()
let match = null;
// index to retrieve the parameters for route from params array
let paramIndex = 0;
while (match = regex.exec(routerPath)) {
// push the first part of the path with param placeholder
routerArray.push(routerPath.substring(0, match.index))
// push the param at paramIndex
routerArray.push(params[paramIndex++]);
// remove the contents from routerPath which are processed
routerPath = routerPath.substring(regex.lastIndex);
// regex is stateful, reset the lastIndex coz routerPath was changed.
regex.lastIndex = 0;
}
// if the recieved route path didn't accept any argumets
if (routerArray.length === 0) {
routerArray.push(routerPath)
}
return routerArray
}
}

现在你可以像这样使用管道了:

<button [routerLink]="'first/:id1/second/:id2' | routerArray: ['1', '2']">Click to Navigate</button>

查看 Example here...

关于 Angular 路线 : URL like/my/:parameter/path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53615762/

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