在TypeScript中调用Angular路由器

RBa*_*iak 7 angular-routing angular

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

<button [routerLink]="['../edit', 14]">Test</button>
Run Code Online (Sandbox Code Playgroud)

所以,如果我在http://localhost/dashboard并点击按钮,我会被重定向到http://localhost/dashboard/edit/14,这正是我所期望的.

现在我需要在Typescript中做同样的事情.我Router在我班上注入了这项服务并尝试了以下方法:

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

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

this.router.navigate([`edit/${item.id}`]);
Run Code Online (Sandbox Code Playgroud)

但没有一个工作,所有这些都将我重定向到我的起始页面,没有任何错误.

是否Router需要一些额外的设置?

Ted*_*rne 10

您需要指定相对于当前路由的路由.以下是如何做到这一点:

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

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

以下是文档描述的relativeTo属性NavigationExtras

  • 从“@Angular/router”导入{ActivatedRoute,Router};// 这就是导入 Route 和 ActivatedRoute 的方式 (2认同)