在TypeScript中调用Angular路由器

前端之家收集整理的这篇文章主要介绍了在TypeScript中调用Angular路由器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在这样的页面中有一个按钮:

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

所以,如果我在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}`]);

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

路由器是否需要一些额外的设置?

解决方法

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

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

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

这里有Docs描述NavigationExtras类的relativeTo属性

猜你在找的Angularjs相关文章