angular 路由
时间: 2023-08-22 16:04:42 浏览: 40
Angular 路由是 Angular 框架提供的一种机制,用于管理应用程序中不同页面之间的导航。它允许你在应用程序中定义不同的路由,每个路由对应一个特定的组件或模块。
要使用 Angular 路由,首先需要在应用程序的根模块中导入 `RouterModule` 并将其添加到 `imports` 数组中。然后,在定义路由之前,你需要创建一个包含路由配置的模块。
路由配置模块可以包含以下内容:
- 导入 `RouterModule` 并使用 `forRoot` 方法来配置根路由。
- 使用 `Routes` 类定义一个路由数组,其中每个路由对象都包含路径和组件的映射关系。
- 将路由数组传递给 `RouterModule.forRoot()` 方法。
例如,以下是一个简单的路由配置示例:
```typescript
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
```
在上面的示例中,我们定义了两个路由。路径为空时,将加载 `HomeComponent` 组件,而路径为 'about' 时,将加载 `AboutComponent` 组件。
最后,你可以在应用程序的模板中使用 `<router-outlet></router-outlet>` 标签来显示当前路由所对应的组件。
这只是 Angular 路由的基本概念,你还可以通过配置更多选项来实现更复杂的路由功能,如路由参数、子路由、路由守卫等。
相关推荐









在 Angular 中,可以通过添加子级路由来实现嵌套路由。以下是添加子级路由的步骤:
1. 在父级路由的定义中,添加一个 children 数组。
typescript
const routes: Routes = [
{
path: 'parent',
component: ParentComponent,
children: [
{
path: 'child',
component: ChildComponent
},
// 添加更多子级路由
]
},
// 添加更多路由
];
2. 在子级路由的定义中,指定子级路由的路径和对应的组件。
typescript
{
path: 'child',
component: ChildComponent
}
3. 在父级组件的模板中,添加一个 router-outlet 元素,用于显示子级路由的组件。
html
<router-outlet></router-outlet>
4. 使用父级路由的路径和子级路由的路径组合成完整的路由路径,即可访问子级路由。
html
Go to child route
注意:子级路由的路径是相对于父级路由的路径而言的。在上面的例子中,子级路由的完整路径是 /parent/child。如果父级路由的路径是 /parent/:id,那么子级路由的完整路径就是 /parent/:id/child。







