简体   繁体   English

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

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

I am following angular official tutorial . 我正在关注有角度的官方教程 This question confused me, but this tutorial did not explain why so. 这个问题使我感到困惑,但是本教程没有解释为什么会这样。

When we click a element, we route to a view/template. 单击元素时,我们将路由到视图/模板。 You can see, we have '/heroes', why we need to add '/' in here? 您可以看到,我们有'/ heroes',为什么我们需要在此处添加'/'? I removed the '/', then the router cannot work. 我删除了“ /”,则路由器无法工作。

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

Here is the router definition, but it does not have '/'. 这是路由器定义,但没有'/'。

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

Assuming you're using <a routerLink="/heroes">Heroes</a> Angular would try to route to yoururl/heroes . 假设您使用的是<a routerLink="/heroes">Heroes</a> Angular会尝试路由到yoururl/heroes Using <a routerLink="heroes">Heroes</a> instead appends the link to your current route. 而是使用<a routerLink="heroes">Heroes</a>将链接附加到当前路线。

Let's say eg you're on this route yoururl/dasboard . 假设您在这条路yoururl/dasboard例如yoururl/dasboard

This would basically navigate to yoururl/heroes 这基本上可以导航到yoururl/heroes

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

While this would navigate to yoururl/dasboard/heroes 虽然这将导航到yoururl/dasboard/heroes

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM