本文介绍了angular笔记路由之angular-router,分享给大家,具体如下:
创建项目
ng new router --routing \\ 加routing参数\\ 会新增一个app-routing.module.ts 文件路由的基本使用
名称 简介 Routes 路由的配置,保存着哪一个URL对应展示哪一个组件和在哪一个RouterOutler展示 RouterOutler 在HTML中标记路由内容呈现的占位符指令 Router 运行时执行的路由对象,可以通过navigate()和navigateByUrl()方法来导航到指定路由 RouterLink 在HTML中声明导航的指令 ActivatedRoute 当前激活的路由对象,保存着当前路由信息,路由地址,路由参数
路由对象图示
路由基本配置
const routes:Routes = [ {path:'',component:HomeComponent}, \\ 注意path里面不要加\线 {path:'app',component:AdminComponent}];路由通配符配置
{path:'**',component:Code404Component}// 配置里面加一条代表没有的都往这里,注意这里不能写在前面,不然angualr的路由会优先匹配这里HTML里面跳转链接
<a [routerLink]="['/']">主页</a><a [routerLink]="['/app']">后台</a><router-outlet></router-outlet>在js里面跳转路由
<input type='button' value='跳转到后台' (click)="toApp()">constructor(private router:Router){ }// 点击事件 toApp(){ this.router.navigate(['/app']) }路由数据传递
1、在查询参数中传递数据
2、在路由路径中传递数据
3、在路由配置中传递数据
复制代码 代码如下:
{path:/product,component:Appcomponent,data:[IsProd:true]} => ActivatedRoute.data[0][IsProd]
参数快照和参数订阅
snapshot 是参数快照当路由进入该组件的时候,然后再点击按钮进入该路由路由里面的的ngOnInit()方法只执行一次,已经被激活,说以第二次这个不会被执行
subscribe 是参数订阅,这个属于RxJs的东西
重定向路由
{path:'',redirectTo:'/home',pathMatch:'full'},子路由
{path:'home',component:HomeComponent,children:[ {path:'',component:IndexComponent} ]},// 记得去HomeComponent,里面添加<router-outlet></router-outlet>指令辅助路由
// html 视图部分<router-outlet></router-outlet><router-outlet name='aux'></router-outlet>//路由配置部分{path:'app',Appcomponet,outlet:'aux'}路由守卫
只有当用户已经登录并拥有一些权限时才能进入
多表单组成的向导,如注册流程,只有满足条件才能进入下一个路由
用户执行操作没有保存,试图离开时候进行相关提示
名称 说明 CanAxtivate 处理导航到某路由 CanDeactivate 处理当前路由离开 Resolve 在路由激活前获取路由数据
1.CanAxtivate的使用
canActivate是一个数组,可以接收多个,当每一个都返回true时候才允许
// 修改路由配置,添加一个属性canActivate{path:'home',component:HomeComponent,children:[ {path:'',component:IndexComponent} ],canActivate:[LoginGuard]},修改NgModuleproviders:[LoginGuard]2.CanDeactivate的使用
// 新建一个文件import {CanDeactivate} from '@angular/router'import {AppComponent} from "../app.component";/** * 处理用户离开 * 接收一个泛型 */export class OutGuard implements CanDeactivate<AppComponent>{ // component 里面保存着AppComponent的数据 canDeactivate(component:AppComponent){ return window.confirm('您还没有保存确定要离开吗?') }}修改路由的配置
{path:'home',component:HomeComponent,children:[ {path:'',component:IndexComponent} ],canActivate:[LoginGuard],canDeactivate:[OutGuard]},providers:[LoginGuard,OutGuard]以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。