Angular提供了一种方式来设置默认路由。在app-routing.module.ts文件中,你可以使用redirectTo关键字来将路由重定向到你指定的组件。
在这个例子中,我们将RouterModule.forRoot()方法中的第一个路由重定向到'home'路径:
app-routing.module.ts:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
注意,这里的redirectTo路径使用的是相对路径。这样做的好处是如果你在将来修改了路由的路径,重定向仍然会按照最新的路径进行。请注意设置pathMatch参数是非常重要的,因为它告诉Angular应该如何匹配路由,这里将其设置为'full',表示必须完全匹配。
现在你已经设置好了默认路由。当用户打开你的应用程序时,它将自动重定向到你指定的组件(在本例中是HomeComponent)。