1. 新建路由模块
ng generate module app-routing --flat --module=app
--flat 生成在src/app
--module=app 配置到app模块
2. 引入所需组件
import { HeroesComponent } from './heroes/heroes.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
//需要使用 RouterModule
中的 Routes
类来配置路由器
import { RouterModule, Routes } from '@angular/router';
3. 定义路由
const routes: Routes = [
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }, //默认空路由
{ path: 'heroes', component: HeroesComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent } //传参路由
];
4. 路由预加载
@NgModule({
//初始化路由器
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
5. 添加路由出口及链接
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
</nav>
<router-outlet></router-outlet>
传参路由的不同点:
1. 链接
<a routerLink="/detail/{{hero.id}}">
2. 路由定义
{ path: 'detail/:id', component: HeroDetailComponent } //传参路由
3. 获取路由参数
a. 导入ActivatedRoute
//保存 HeroDetailComponent 实例的路由信息import { ActivatedRoute } from '@angular/router';
//返回上个视图
import { Location } from '@angular/common';
b. 创建私有实例
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) { }
c. 调用实例的方法
ngOnInit() {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
//route.snapshot 是一个路由信息的静态快照
//paramMap 是一个从 URL 中提取的路由参数值的字典
//JS 的 (+) 操作符会把字符串转换成数字
.subscribe(hero => this.hero = hero);
}
goBack(): void {
this.location.back();
}