angular学习6-导航与路由(1)

本文详细介绍了Angular中的路由配置与使用,包括常规路由、带参数路由、路由重定向、通配符路由、路由器链接及ActivatedRoute服务的使用。同时,讲解了如何通过paramMap获取路由参数,Navigate方法实现路由跳转,以及路由间数据交互的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

路由配置

src/app/app.module.ts

cconst Routes:Routes = [
{path:'crisis-center'm=,component:CrisisCenterComponent},
{path:'hero/:id',component:HeroListComponent},
{path:'/heroes',component:HeroesComponent},
{path:'',redirectTo:'/heroes',pathMatch:'full'},
{path:'**',component:PageNotFoundComponent}
]
路由路径路由用法
{path:" crisis-center"}常规路由写法
{path:‘hero/:id’}带参数路由,例子 localhost:3000/hero/37
{path:’ ‘,redirectTo:’/heroes’}路由重定向到heroes
**通配选择符,找不到任何页面的时候会转到这里

路由器链接

<a routerLink="/heroes" routerLinkActive="active"></a>
<a routerLink="/hero/16"></a>

ActivatedRoute-路由服务

import {Router,ActivatedRoute,ParamMap} from '@angular/router'
import {switchMap} from 'rxjs/operators'
//src/app/heroes/hero-detail.component.ts
//依赖注入
hero$;
hero1$
constructor(private:ActivatedRoute,private router:Router){
}
ngOnInit(){
	this.hero$ = this.route.snapshot.paramMap.get('id')
	//或者
	this.hero1$ = this.router.paramMap.pipe(
		switchMap((params:ParamMap)=>{
			params.get('id')
		})
	)
	//或者
	this.hero2$ = this.router.paramMap.pipe(
		switchMap((params:ParamMap)=>{
			return of(params.get('id'))
			})
	).subscribe((id)=>{
		console.log('id')
	})

}

由于paramMap是一个Observable对象,所以可以用rxjs这个库去获取数据流

ParamMap API

成员说明
has(name)判断参数列表中是否有这个参数,是返回true
get(name)如果paramMap中有参数名对对应的参数值,返回参数值,否则返回null,如果参数值是一个数组,返回它的第一个值
getAll(name)如果一个参数名可能返回多个参数值,用getAll
keys返回这个map中所有参数名返回的数组

Navigate 跳转路由

//跳转到 /hero/15/
this.router.nativate(['hero',15])
//向想要跳转的路由传递参数
this.router.navigate(['hero',{id:15,foo:'foo'}])
路由和路由之间的数据交互方式
在路由跳转的时候附带参数,引入服务,服务是一个单例,两个路由之间可以通过服务进行沟通,也可以看成两个独立组件间的数据沟通。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值