angular学习总结-路由和路由守卫

通过命令新建页面news:

ng g page news

会在src/app目录下自动生成以下文件,并更新app-routing.module.ts总路由文件。
在这里插入图片描述
再来看看app-routing.module.ts文件,已自动配置好了新页面的路由。
在这里插入图片描述
从路由可以看出,我创建了两个页面,一个home,一个news。
现在想从home页面跳转到news页面去,并携带参数,该怎么传呢?

路由跳转和传参

方式一:

设定:home页面跳转news页面需要传递参数empNo。

第一步:修改路由。

src/app/app-routing.module.ts

{
    path: 'news/:empNo',
    loadChildren: () => import('./news/news.module').then( m => m.NewsPageModule)
  }
第二步:跳转路由传参。

src/app/home/home.page.ts

clickMe() {
    console.log('点我跳转');
    this.router.navigate(['/news','9295'])
  }
第二步:目标页面接收参数。

src/app/news/news.page.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-news',
  templateUrl: './news.page.html',
  styleUrls: ['./news.page.scss'],
})
export class NewsPage implements OnInit {

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    const routeParams=this.route.snapshot.params
    console.log(routeParams)
  }

}

打印结果:

{empNo: '3'}
方式二:

设定:home页面跳转news页面需要传递参数对象。

第一步:跳转路由传参。

src/app/home/home.page.ts

 clickMe() {
    console.log('点我跳转');
    this.router.navigate(['/news'],{
      queryParams:{
        name:'张三',
        id:'1234567801',
      }
    })
  }
第二步:目标页面接收参数。

src/app/news/news.page.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-news',
  templateUrl: './news.page.html',
  styleUrls: ['./news.page.scss'],
})
export class NewsPage implements OnInit {

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    const routeParams=this.route.snapshot.queryParams
    console.log(routeParams)
  }

}

打印结果:

{name: '张三', id: '1234567801'}

路由守卫

路由守卫会对路由跳转进行拦截。

像移动端手机物理返回键的监听控制,可以通过路由守卫来控制要返回到哪个路由页面。
还常用这些场景:

1.该用户可能无权导航到目标组件。
2.可能用户得先登录(认证)。
3.在显示目标组件前,你可能得先获取某些数据。
4.在离开组件前,你可能要先保存修改。
5.你可能要询问用户:你是否要放弃本次更改,而不用保存它们?

路由器可以支持多种守卫接口:

  • 用CanActivate来处理导航到某路由的情况。

  • 用CanActivateChild来处理导航到某子路由的情况。

  • 用CanDeactivate来处理从当前路由离开的情况.

  • 用Resolve在路由激活之前获取路由数据。

  • 用CanLoad来处理异步导航到某特性模块的情况。

第一步:执行命令,生成路由守卫。
ng g guard home

然后就会出现选择器,选择你需要的守卫接口。
在这里插入图片描述
然后就生成home.guard.ts文件。
在这里插入图片描述

第二步:配置路由守卫。

配置home-routing.module.ts路由守卫。
在这里插入图片描述

第三步:操作路由守卫。

我用的比较多的是canDeactivate,从当前路由离开时会进行触发。

1.先对home.guard.ts进行配置。

在这里插入图片描述

2.在home.page.ts中配置canLeave方法。
 canLeave(){
    console.log('--canLeave--')
    return false
  }

在这里插入图片描述
效果:
点击页面跳转按钮,
页面未跳转,并打印
–canLeave–

说明路由守卫控制成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值