创建一个routing模块 ng g m 模块名
引入 RouterModule, Routes模块
import { RouterModule, Routes} from '@angular/router';
import { ActivatedRoute } from '@angular/router';
// 引入 RouterModule, Routes模块
// 引入ActivatedRoute获取路由传的参数
引入要跳转的模块
// 如果想要跳转哪一个组件,必须在此引入组件方可使用
import { AaComponent } from '../../comp/aa/aa.component';
设置路由,在routes里边添加元素,元素的类型为对象
每一个元素中包含了 { path: 'aa', component: AaComponent }
// path代表了跳转的路径, component 代表要切换的组件
// 1,路由的 routes 是一个数组,按照数组的索引顺序进行路由配置
// 2,** 通配路由,即为如果按照索引顺序解析到该路由配置时,无条件执行
// 3,路由重定向 redirectTo:'重定向的路径';
// 4,路由的精度匹配 pathMatch,如果值为full 则完全匹配,如果值为prefix 则为不完全匹配,可以匹配以path开头的所有路径 path:'bb' 可以匹配 /bb/s/wqe/sa,要和重定向配合使用
const routes: Routes = [
{ path: '', component: NbaComponent }
]
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
declarations: [],
exports: [RouterModule]
})
export class AppRoutingModule { }
最下方配置;
配置完成后给标签添加 route-link 属性,属性值为path path内不用带 / route-link 中的属性值要带 /
在要显示路由的位置写上 <router-outlet></router-outlet> 标签承载 路由跳转的组件 此标签可添加name值
其他特殊路由的写法
// 辅助路由,可以单独的把组件内容显示在指定的outlet中
{ path: 'ww', component: PipeComponent, outlet: 'wang'},
// 路由传值,在路由配置中设置data
{ path: 'zhi', component: ZhiComponent, data: [ { name: '詹姆斯', age: 25 } ] },
// 路由传值,把要传的值写在路径中
{ path: 'zhi2/:name/:age', component: Zhi2Component },
// 设置子路由
{ path: 'father', component: FatherComponent, children: [
{ path: 'son1', component: Son1Component },
{ path: 'son2', component: Son2Component }
]},