路由跳转方式 总的大概分为两种
两种写法
<a routerLink="./component-a">跳转a组件</a>
<a [routerLink]="['./component-a']" >跳转a组件</a>
定义路由
{path: 'component-a', component: ComponentAComponent}
定义路由出口
<router-outlet></router-outlet>
需要注入两个服务
Router 一个提供导航和操纵 URL 能力的 NgModule。
ActivatedRoute: angular中ActivatedRoute
Router.navigate返回值是一个promise 值为boolean类型,是否跳转成功
constructor(public router:Router,public activeRoute:ActivatedRoute) { }
toComponentB(){
this.router.navigate(['component-b'] , {relativeTo: this.activeRoute}).then(r => console.log(r))
}
跳转按钮
<button nz-button nzType="primary" (click)="toComponentB()">跳转b组件</button>
定义路由
{path: 'component-b', component: ComponentBComponent}
每种跳转方式都有两种,共计有四种路由传参方式
第一种:
在路由上添加查询参数,定义路由未进行修改
{path: 'component-a', component: ComponentAComponent}
<a routerLink="./component-a" [queryParams]="{id:'1'}">跳转a组件</a>
页面地址://localhost:4200/router-study/component-a?id=1
<a [routerLink]="['./component-a' ,{id:'2'}]" routerLinkActive="active">跳转a组件</a>
页面地址 http://localhost:4200/router-study/component-a;id=2
两种写法的接受方式不同
接收:
id: string = ''
constructor(public activeRoute: ActivatedRoute) {
}
ngOnInit(): void {
this.activeRoute.queryParams.subscribe(res => {
this.id = res['id']
}
)
this.activeRoute.params.subscribe(res => {
this.id = res?.id
})
}
第二种:
动态路由,定义路由进行修改
{path: 'component-a/:id', component: ComponentAComponent}
<a [routerLink]="['./component-a' ,'2']" routerLinkActive="active">跳转a组件</a>
页面地址 http://localhost:4200/router-study/component-a/2
接收传参方式:
this.activeRoute.params.subscribe(res => {
this.id = res?.id
})
第一种:在路由上添加查询参数
this.router.navigate(['component-b',{id:'3'}] , {relativeTo: this.activeRoute}).then(r => console.log(r))
http://localhost:4200/router-study/component-b;id=3
接收:两种方式都可以获得到参数
this.activateRoute.params.subscribe(res => {
this.id = res['id']
})
if (this.activateRoute.snapshot.paramMap.get('id')) {
this.id = this.activateRoute.snapshot.paramMap.get('id')
}
第二种 动态路由
定义路由进行修改
{path: 'component-b/:id', component: ComponentBComponent}
this.router.navigate(['component-b','3'] , {relativeTo: this.activeRoute}).then(r => console.log(r))
http://localhost:4200/router-study/component-b/3
接收:两种方式都可以获得到参数
this.activateRoute.params.subscribe(res => {
this.id = res['id']
})
if (this.activateRoute.snapshot.paramMap.get('id')) {
this.id = this.activateRoute.snapshot.paramMap.get('id')
}