为什么我需要将“/”添加到 routerLink 但我们在路由器定义中没有“/”?

Why I need to add '/' to routerLink but we do not have '/' in router definination?

我正在关注 angular official tutorial。这个问题让我一头雾水,但是这个教程并没有解释为什么会这样。

当我们点击一​​个元素时,我们会路由到 view/template。你可以看到,我们有'/heroes',为什么我们要在这里添加'/'?我把'/'去掉了,路由器就不能用了

template: `
   <h1>{{title}}</h1>
   <nav>
     <a routerLink="/dashboard">Dashboard</a>
     <a routerLink="/heroes">Heroes</a>
   </nav>
   <router-outlet></router-outlet>

这里是路由器定义,但是没有'/'。

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard',  component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes',     component: HeroesComponent }
];

假设您正在使用 <a routerLink="/heroes">Heroes</a> Angular 会尝试路由到 yoururl/heroes。使用 <a routerLink="heroes">Heroes</a> 而是将 link 附加到您当前的路线。

比方说你在这条路上 yoururl/dasboard.

这基本上会导航到 yoururl/heroes

<a routerLink="/heroes">Heroes</a>

虽然这会导航到 yoururl/dasboard/heroes

<a routerLink="heroes">Heroes</a>