5.路由重定向和二级路由如何配置
时间: 2024-05-15 22:16:55 浏览: 10
路由重定向是指将某个 URL 重定向到另一个 URL 的操作。在 Angular 中,可以使用 `redirectTo` 属性来配置路由重定向。例如,假设我们有一个路由定义如下:
```
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '**', component: NotFoundComponent }
];
```
上面的路由定义中,第一个路由将空路径重定向到 `/home` 路径;第二个和第三个路由分别匹配 `/home` 和 `/about` 路径,并渲染对应的组件;最后一个路由使用双星号通配符匹配所有未匹配到的路径,并渲染一个 404 页面。
二级路由是指在一个路由下再嵌套一个子路由。在 Angular 中,可以使用 `children` 属性来配置二级路由。例如,假设我们要在 `/about` 路径下添加一个子路由:
```
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent,
children: [
{ path: '', component: AboutHomeComponent },
{ path: 'info', component: AboutInfoComponent }
]
},
{ path: '**', component: NotFoundComponent }
];
```
上面的路由定义中,`/about` 路径下定义了两个子路由:空路径对应的组件是 `AboutHomeComponent`,`/info` 路径对应的组件是 `AboutInfoComponent`。这样,当用户访问 `/about` 路径时,会默认渲染 `AboutHomeComponent` 组件;当用户访问 `/about/info` 路径时,会渲染 `AboutInfoComponent` 组件。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)