angular路由导航配置
开发工具:VSCode
打开终端输入命令创建crisis-list和hero-list组件
ng generate component crisis-list
ng generate component hero-list
再app文件夹下面自动创建了两个组件
要使用路由器,必须先注册来自@angular/route包中的RouterModule,定义一个路由数组appRoutes并且把它传给RouterModule.forRoot()方法。他会返回一个模块,其中包含配置好的Router服务,以及路由库里所需要的提供包这些。一旦启动了应用,Router就会根据当前的浏览器URL地址进行首次导航访问。在app.module.ts文件里
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CrisisListComponent } from './crisis-list/crisis-list.component';
import { HeroListComponent } from './hero-list/hero-list.component';
import {RouterModule, Routes} from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', component: HeroListComponent },
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent },
];
@NgModule({
declarations: [
AppComponent,
CrisisListComponent,
HeroListComponent,
NotFoundComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <-- debugging purposes only
)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
路由出口,angular的路由出口需要依赖于
<router-outlet></router-outlet>
在app.component.html编写相关的html代码 并且超链接的点击事件
<h1>父页面</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<!--路由出口-->
<router-outlet></router-outlet>
routerLink属性的后面值是和app.module.ts里得路由规则进行匹配跳转相应的路径页面,routerLinkActive属性在这篇文章不做解释 不影响
现在来说说配置路由规则,回到app.module.ts文件里面
path: 'crisis-center', component: CrisisListComponent
path表示url显示的路由,例如:http://localhost:4200/crisis-center,component表示组件名称,指到那个组件就跳转哪个组件模板(页面)
path: '', redirectTo: '/heroes', pathMatch: 'full'
path为'' 表示不输入规则进行访问时会匹配到此规则,例如http://localhost:4200,但hi为了避免没有组件可访问,加上redirceTo重定向路由,意思是如果在地址栏直接输入http://localhost:4200他会默认访问http://localhost:4200/heroes
path: '**', component: NotFoundComponent
这个路由规则比较特殊,当你输入错的路由,全部没有匹配到时就会访问到此规则,通常拿来做404-not-find-page页面
注意三种路由规则依次排序顺序,不能乱,
const appRoutes: Routes = [
{ path: 'crisis-center', component: CrisisListComponent },
{ path: 'heroes', component: HeroListComponent },
{ path: '', redirectTo: '/heroes', pathMatch: 'full' },
{ path: '**', component: NotFoundComponent },
];
看效果: