angular 路由跳转以及传参

1. 路由跳转方式一: /路由?id='001' 方式 -- queryParams 方式

 路由配置:{ path: 'details', component: bookDetailsComponent }

   a.  指令跳转:

  <a [routerLink]="['/details']" [queryParams]="{id: item.id}" style="color:blue; font-size: 12px;cursor:pointer">查看详情</a>

  routerLink: 跳转的路由,数组形式,传参有两种写法: 1. 使用 [queryParams]="{id: item.id}", 2. [routerLink]="['/details', id]", 数组第一个值是            路由,第二个值是要传递的参数

  b. js 实现跳转:

  

其中 this.router 是 Router 的实例

import  { Router } from '@angular/router'

constructor(private router: Router) {
 }
 jumpDetial(bookId: string): void {
        this.router.navigate(['/details'], {
            queryParams: {
                id: bookId
            }
        })
    }

this.router.navigate(['user', 1]); 以根路由为起点跳转

this.router.navigate(['user', 1],{relativeTo: route}); 默认值为根路由,设置后相对当前路由跳转,跳转到子路由

this.router.navigate(['user', 1],{ queryParams: { id: 1 } }); 路由中传参数 /user/1?id=1

this.router.navigate(['view', 1], { preserveQueryParams: true }); 默认值为false,设为true,保留之前路由中的查询参数/user?id=1 to /view?id=1

this.router.navigate(['user', 1],{ fragment: 'top' }); 路由中锚点跳转 /user/1#top

this.router.navigate(['/view'], { preserveFragment: true }); 默认值为false,设为true,保留之前路由中的锚点/user/1#top to /view#top

this.router.navigate(['/user',1], { skipLocationChange: true }); 默认值为false,设为true路由跳转时浏览器中的url会保持不变,但是传入的参数依然有效

this.router.navigate(['/user',1], { replaceUrl: true }); 未设置时默认为true,设置为false路由不会进行跳转

2. 以 /路由/参数  的方式跳转 -- snapshot方式

 路由配置:  { path: 'details/:id', component: bookDetailsComponent }

1. 指令跳转传参:

  

  <a [routerLink]="['/details', item.id]"</a>

2. js 跳转:

  

  this.router.navigate(['/details', '1']

3. 获取参数

a. 快照方式获取参数 snapshot

this.queryParams = this.route.snapshot.params['id']

b. queryParams 方式获取参数

this.route.queryParams.subscribe(params=>{
  this.queryParams = params['id']
    console.log(this.queryParams)
})

猜你喜欢

转载自www.cnblogs.com/monkey-K/p/11455272.html