- 一、静态路由
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CrisisListComponent} from './crisis-list/crisis-list.component';
import { HeroDetailComponent} from './hero-detail/hero-detail.component';
const routes: Routes = [
{path: 'crisis-center', component: CrisisListComponent},
{path: 'hero', component: HeroDetailComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
Crisis Center
Heroes
- 二、动态路由传参
- 模板简单传参
app-routing.module.ts
const routes: Routes = [
{path: 'crisis-center', component: CrisisListComponent},
{path: 'hero/:id', component: HeroDetailComponent},
];
app.component.html
Crisis Center
Heroes
hero-detail.component.ts
const id = this.route.snapshot.paramMap.get('id');
console.log(id);
- 模板传递对象
app-routing.module.ts
const routes: Routes = [
{path: 'crisis-center', component: CrisisListComponent},
{path: 'hero', component: HeroDetailComponent},
];
app.component.html
Crisis Center
Heroes
hero-detail.component.ts
this.route.queryParamMap.subscribe((params: Params) => {
console.log(params.params)
})
- Router的navigate方法传参
app-routing.module.ts
const routes: Routes = [
{path: 'crisis-center', component: CrisisListComponent},
{path: 'hero', component: HeroDetailComponent},
];
app.component.html
app.component.ts
heroClick() {
this.router.navigate(['/hero', {id: 1, name: 'name'}])
}
hero-detail.component.ts
this.route.paramMap.subscribe((p: Params) => {
console.log(p.params)
})
- 三、子路由
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProductComponent } from './product/product.component';
import { SettingComponent } from './setting/setting.component';
import { ListComponent } from './product/list/list.component';
import { DetailComponent } from './product/detail/detail.component';
const routes: Routes = [
{
path: 'product',
component: ProductComponent,
children: [
{path: 'list', component: ListComponent},
{path: 'detail', component: DetailComponent}
]
},
{path: 'setting', component: SettingComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.component.html
商品
设置
product.component.html
- 三、路由守卫
参考@llaaakk博文地址