Angular路由参数传递 Angular路由参数传递

一、路由时传递参数的方式

1、在查询参数中传递数据

//页面
<a routerLink="/product" [queryParams]="{id:1}">商品详情</a>
//ts获取参数
export class ProductComponent implements OnInit {
  private productId: number;
  constructor(private routeInfo: ActivatedRoute) { }
  ngOnInit() {
    this.productId = this.routeInfo.snapshot.queryParams['id'];
  }
}

相应的后台获取是:ActivedRoute.queryParams[id]

2、在路由路径中传递数据

//页面
<a [routerLink]="['product', 1]">商品详情</a>
//后台页面,先修改路由定义,app-routing.modules.ts中
const routes: Routes = [
  {path: 'product/:id', component: ProductComponent},
  {path: '**', component: HomeComponent},
];

this.productId = this.routeInfo.snapshot.params['id'];

在路由定义时,定义为:product/:id,其中“:id”代表参数

3、在路由配置中传递数据

//页面
<input type="button" value="商品详情" (click)='toProductDetails()' >

页面跳转:

constructor(  
    private router: Router,   //这里需要注入Router模块  
){}  
  
toProductDetails(){  
    //这是在html中绑定的click跳转事件  
    this.router.navigate(['product-detail'], {  
        queryParams: {  
            productId: '1',  
            title: 'moon'  
        }  
    });  
}

接收参数:

constructor(
    private activatedRoute: ActivatedRoute,   //这里需要注入ActivatedRoute模块
) {
    activatedRoute.queryParams.subscribe(queryParams => {
        let productId = queryParams.productId;
        let title = queryParams.title;
    });
}

二、后台接收路由参数方式

1、snapshot和subscribe两种,区别在于在路由地址不变的情况下,若参数发送变化后者所接收的参数也会随之变化,前者不变。

三、路由重定向

访问一个特定的地址时,会将其重定向到另一个指定的地址

1 //在定义路由时 
2  {path: '', redirectTo: '/home', pathMatch: 'full' },
3  {path: 'home', component : HomeComponent},

参考:

Angular路由参数传递

angular4.0中路由传递参数、获取参数最nice的写法

猜你喜欢

转载自www.cnblogs.com/Jason-Xiang/p/8985004.html
今日推荐