【问题标题】:Why I need to add '/' to routerLink but we do not have '/' in router definination?为什么我需要在 routerLink 中添加“/”,但路由器定义中没有“/”?
【发布时间】:2017-07-29 22:19:25
【问题描述】:

我关注angular official tutorial。这个问题让我很困惑,但是本教程没有解释为什么会这样。

当我们点击一​​个元素时,我们会路由到一个视图/模板。您可以看到,我们有'/ 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 }
];

【问题讨论】:

  • 澄清一下:你问为什么要写/heroes而不是heroes
  • 是的。为什么在 routerLink 中使用“/heroes”?
  • 因为只有'heros' 是相对于当前路由的'/heros' 是相对于应用程序的根目录
  • @0mpurdy 为什么我们不在此处添加“/”? { 路径:“英雄”,组件:英雄组件 }
  • 因为您正在描述一个路径列表,这些路径都是相对的

标签: angular router


【解决方案1】:

假设你使用&lt;a routerLink="/heroes"&gt;Heroes&lt;/a&gt;,Angular 会尝试路由到yoururl/heroes。使用 &lt;a routerLink="heroes"&gt;Heroes&lt;/a&gt; 代替将链接附加到您当前的路线。

比如说,例如你在这条路线上yoururl/dasboard

这基本上会导航到yoururl/heroes

&lt;a routerLink="/heroes"&gt;Heroes&lt;/a&gt;

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

&lt;a routerLink="heroes"&gt;Heroes&lt;/a&gt;

【讨论】:

  • 这个Heroes 路由到你的url/heroes
  • 好像我弄错了。在这种情况下,它应该与我所写的完全相反。我将相应地进行编辑。但无论如何,我试图解释的尝试仍然应该是正确的。这只是关于相对路径路由。
  • 谢谢。在更多用户支持您的答案后。我会接受你的回答,因为我没有能力检查你的解释是否正确。我很感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-14
  • 2016-07-18
  • 2019-03-10
  • 1970-01-01
相关资源
最近更新 更多