angular路由学习
- 使用指令自动配置路由
- 不使用指令自己配置:
1.首先在根目录src/app/app.module.ts (import)文件引入
import { RouterModule, Routes } from '@angular/router';
2.在下面注入
@NgModule(
imports:[
AppRoutingModule
]
)
3.在相应的html文件编写路由出口,这个出口会显示路由的组件
<router-outlet></router-outlet>
配置路由
单单引入路由是不够的,还需要在app.Modules.ts文件中引入通过路由跳转的组件,以及相应的路径(随着项目变大功能变多,以下内容推荐写在routing .module.ts文件中)
import { CrisisListComponent } from './crisis-list/crisis-list.component';
declarations: [
CrisisListComponent,
],
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
];
其中path是自定义路由的名字,通过它访问哪个相应的组件
路由出口
- html文件中可通过
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
实现页面跳转,跳转显示的组件会在路由出口处显示
定义通配符路由
由于编写的路由只有有限的url,当输入不存在的url会出现错误,所以我们需要使用通配符拦截无效路由,当匹配失败时,就会访问此路由
{ path: '**', component: PageNotFoundComponent }
定义默认路由
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
pathMatch重定向,具体用法看官网。今天粗略学习。
路由参数
{ path: 'hero/:id', component: HeroDetailComponent }
<a [routerLink]="['/hero', hero.id]">