- 使用angular+ cli 创建一个项目文件:ng new router-app;
- 如果创建时 选择 不设置路由;则可以在需要加入路由的时候进行单独安装;
-
1 ng g module app-routing --flat --module=app 2 3 // -- flat 将该文件放入到scr/app目录下 4 // --module=app 将路由注册到AppModule 的 imports数组中
- 使用cli 创建路由后,app-routing.module.ts
-
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ // {path:'', redirectTo: '', pathMatch: 'full'} 路由重定向,将需要展示的页面作为默认页面,pathMatch = 'full';只有在默认路由整个URL等于''的时候满足重定向 // {path: '**' , component: pageNoComponent} // 当没有匹配的路径或错误的路径时,显示的组件;一般可作为404页面 ]; //.forRoot()-- 在应用的顶级配置路由器,提供路由需要的服务提供商和指令,基于浏览器当前URL执行首次导航 // enableTarcing -- 路由事件,查看导航在生命周期中发生的事件,并输出到控制台 @NgModule({ imports: [ RouterModule.forRoot(routes,{enableTracing: true}) ], exports: [RouterModule] }) export class AppRoutingModule { }
- AppModule.ts文件
-
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule // 导入路由 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
- 简单路由使用
-
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; // 第一步,导入组件,生成组件方法可使用命令ng g component <name>;或者其他方法(如非要自己手动生成,也是阔以的) import { CrisisListComponent } from './crisis-list/crisis-list.component'; import { HeroListComponent } from './hero-list/hero-list.component'; import { PageNotFoundComponent } from './page-not-found/page-not-found.component'; // 第二步,配置路由,由于路由优先匹配策略,所以空路径,通用路径放置在最后 const routes: Routes = [ { path: 'crisis-center', component: CrisisListComponent}, { path: 'heroes', component: HeroListComponent}, {path:'', redirectTo: '', pathMatch: 'full'}, // 导航空路径至默认路由 {path: '**' , component: PageNotFoundComponent} // 处理无效路径 ]; //.forRoot()-- 在应用的顶级配置路由器,提供路由需要的服务提供商和指令,基于浏览器当前URL执行首次导航 // enableTarcing -- 查看导航在生命周期中发生的事件,并输出到控制台 @NgModule({ imports: [ RouterModule.forRoot(routes,{enableTracing: true}) ], exports: [RouterModule] }) export class AppRoutingModule { }
- 视图
-
<!--The content below is only a placeholder and can be replaced.--> <h1>Angular Router</h1> <nav> <!-- 路由跳转一 --> <a [routerLink]="[ '/crisis-center' ]" routerLinkActive="active">Crisis Center</a> <a [routerLink]="[ '/heroes' ]" routerLinkActive="active">heroes</a> <!-- 路由跳转二 --> <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a> <a routerLink="/heroes" routerLinkActive="active">heroes</a> </nav> <!-- 路由出口,占位符,可将显示在出口的组件显示在这里 --> <router-outlet></router-outlet>
-
原文地址:https://www.cnblogs.com/gushiyoyo/p/11249893.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。