- 创建路由模块:
- 使用Angular CLI命令创建路由模块,例如在项目根目录下运行
ng generate module app - routing --flat --module=app
。--flat
选项表示将路由模块文件放在项目根目录下,--module=app
表示将此路由模块注册到 app.module.ts
中。
- 创建完成后,会生成一个类似
app - routing.module.ts
的文件。
- 配置路由模块:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
- 定义路由数组
Routes
,每个路由对象包含 path
(路径)和 component
(对应的组件)。例如:
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
- 在
@NgModule
装饰器中配置 RouterModule.forRoot(routes)
,完整代码如下:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
- 设置不同路径对应的组件:
- 如上述路由数组
routes
定义中,path
为路径,component
为该路径对应的组件。例如 { path: 'home', component: HomeComponent }
表示当路径为 home
时,加载 HomeComponent
组件。
- 可以设置默认路径,通过将
path
设置为空字符串 ''
,并在 redirectTo
中指定重定向的路径。例如:
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
pathMatch: 'full'
表示只有在完整路径匹配空字符串时才进行重定向。
- 处理路由参数:
- 定义带参数的路由:在
path
中使用冒号 :
定义参数,例如:
const routes: Routes = [
{ path: 'user/:id', component: UserComponent }
];
- 在组件中获取参数:在对应的组件(如
UserComponent
)中,通过注入 ActivatedRoute
服务来获取参数。例如:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app - user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
userId: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.userId = params.get('id');
});
}
}
- 传递查询参数:查询参数通过
?
后接参数名和值的方式传递,例如 example.com/user?id=123&name=John
。在组件中获取查询参数同样通过 ActivatedRoute
,示例如下:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app - user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
userId: string;
userName: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.queryParamMap.subscribe(params => {
this.userId = params.get('id');
this.userName = params.get('name');
});
}
}