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

路由配置

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'}])

路由和路由之间的数据交互方式

在路由跳转的时候附带参数,引入服务,服务是一个单例,两个路由之间可以通过服务进行沟通,也可以看成两个独立组件间的数据沟通。

猜你喜欢

转载自blog.csdn.net/gexiaopipi/article/details/89161940