在 TypeScript 中调用 Angular 路由器

Calling the Angular router in TypeScript

我在这样的页面中有一个按钮:

<button [routerLink]="['../edit', 14]">Test</button>

因此,如果我在 http://localhost/dashboard 并单击按钮,我将被重定向到 http://localhost/dashboard/edit/14,这正是我所期望的。

现在我需要在 Typescript 中做同样的事情。我在 class 中注入了 Router 服务并尝试了以下操作:

this.router.navigate([`../edit/${item.id}`]);

this.router.navigate([`/edit/${item.id}`]);

this.router.navigate([`edit/${item.id}`]);

但是 none 正在工作,所有这些都将我重定向到我的起始页面,没有任何错误。

Router 需要一些额外的设置吗?

记得在您的 app.module.ts:

上添加子路由
RouterModule.forRoot(
    [{
        path: 'dashboard',
        component: Dashboard,
        children: [
            {
                path: 'edit/:id',
                component: EditComponent,
            }]
    }])

您需要指定您正在相对于当前路线进行路由。这是如何做到的:

@Component({...})
class ChildComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  go() {
    this.router.navigate([`../edit/${item.id}`], { relativeTo: this.route });
  }
}

这里是 Docs 描述 NavigationExtras class

的 relativeTo 属性