Angular路由參數傳遞


一、路由時傳遞參數的方式

1、在查詢參數中傳遞數據,如

 1 //前台頁面
 2 <a routerLink="/product" [queryParams]="{id:1}">商品詳情</a>
 3 //后台頁面獲取參數
 4 export class ProductComponent implements OnInit {
 5   private productId: number;
 6   constructor(private routeInfo: ActivatedRoute) { }
 7   ngOnInit() {
 8     this.productId = this.routeInfo.snapshot.queryParams['id'];
 9   }
10 }

相應的后台獲取是: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'];

在路由定義時,定義為

3、在路由配置中傳遞數據,

1 //前台頁面
2 <input type="button" value="商品詳情" (click)='toProductDetails()' >
3 //后台頁面
4  toProductDetails() {
5     this.router.navigate(['/product', 2]);
6   }
7 this.routeInfo.params.subscribe((params: Params) => this.productId = params['id']);

 

二、后台接收路由參數方式

1、snapshot和subscribe兩種,區別在於在路由地址不變的情況下,若參數發送變化后者所接收的參數也會隨之變化,前者不變。

 

三、路由重定向

訪問一個特定的地址時,會將其重定向到另一個指定的地址

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM