Angular 路由:URL 像 /my/:parameter/path

Raf*_*SCS 2 url-parameters angular angular-router angular7

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

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

有没有办法在/users/1/edit不使用字符串插值的情况下获得输出?

Joh*_*Rin 5

你可以这样尝试: [routerLink]="['/user/', 1, '/edit']"

更一般地,您可以像这样放置 id 参数:

[routerLink]="['/user', <your param 1>, 'edit', <your param 2>]"


xyz*_*xyz 5

我相信你的这个问题是你另一个问题的延伸 在这里,您的要求是获取一个数组,该数组根据您要传递的参数正确转换。我的意思是:

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

const routes: Routes = [
  {path: "first/:id1/second/:id2", component: HelloComponent}
]
Run Code Online (Sandbox Code Playgroud)

在 a 中使用它时[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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<button [routerLink]="'first/:id1/second/:id2' | routerArray: ['1', '2']">Click to Navigate</button>
Run Code Online (Sandbox Code Playgroud)

在此处查看示例...