【问题标题】:Angular 4 routing: navigate to home pageAngular 4 路由:导航到主页
【发布时间】:2020-08-26 06:50:17
【问题描述】:

我定义了以下路线:

const appRoutes: Routes = [
  { path: 'signup', component: SignupComponent },
  { path: 'home', component: HomeComponent },
  { path: '**', component: HomeComponent }

];

访问www.mysite.com 会显示我的HomeComponent,这很好。但是当我点击我的菜单链接导航回主页时,它会将我带到www.mysite.com/home

链接代码如下:

<a href="home" [routerLink]="['home']" class="nav-link active">Home</a>

如何使此链接导航到主 URL www.mysite.com

【问题讨论】:

  • 你可以试试&lt;a href="home" [routerLink]="['/']" class="nav-link active"&gt;Home&lt;/a&gt;
  • 试过了,结果一样:(

标签: angular angular-routing angular4-router


【解决方案1】:

您需要使用空字符串添加路由,请参见下面的示例

const appRoutes: Routes = [
  { path: 'signup', component: SignupComponent },
  { path: 'home', component: HomeComponent },
  { path: '', component: HomeComponent }
  { path: '**', component: HomeComponent }
];

在角度 docs 中,它在属性标题下提到:

path?: string 要匹配的路径。不能与 自定义匹配器功能。使用路由器匹配的 URL 字符串 符号。可以是匹配任何 URL 的通配符 (**)(请参阅用法 以下注释)。默认为“/”(根路径)。

然后将链接更新为:

&lt;a href="home" [routerLink]="['/']" class="nav-link active"&gt;Home&lt;/a&gt;

【讨论】:

    【解决方案2】:

    您正在定义 home 路由,并且您的链接指向 /home,因此行为就是您告诉 Angular 做的事情。

    如果您想导航到 /,请将 html 更改为 &lt;a [routerLink]="['/']" class="nav-link active"&gt;Home&lt;/a&gt;

    另外,您必须更改路由配置:

    const appRoutes: Routes = [
      { path: 'signup', component: SignupComponent },
      { path: 'home', component: HomeComponent },
      { path: '', component: HomeComponent, pathMatch: 'full' } // patchMath is important with empty route, otherwise any route would match
      { path: '**', redirectTo: '/' } // so if you want to access "/foo123", the url will change to "/", so the user wouldn't see a non existing url in the address bar.
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      相关资源
      最近更新 更多