angular 路由傳參的三種方式

1.問號後面帶的參數

url:http://localhost:4200/news?key=japan

html調用方法:

<a [routerLink]="['/news']" [queryParams]="{key: 'japan'}">跳轉</a>

ts調用方法:

private router: Router

this.router.navigate(['/news'], {queryParams: {key : 'japan'}});

獲取參數方法:

private route: ActivatedRoute;

this.route.queryParams.subscribe(queryParams=> {
   console.log(queryParams.key);
});

const key = this.route.snapshot.queryParams['key'];

console.log("key", key);

2.路由路徑傳參

url:http://localhost:4200/news/japan (注意:這裏的路由參數是必須的)

路由路徑配置:

path: 'news/:key',
component: NewsComponent

html調用方法:

<a [routerLink]="['/news', 'japan']">跳轉</a>

ts調用方法:

private router: Router

this.router.navigate(['/news', 'japan']);

獲取參數方法:

this.route.params.subscribe(params => {
  console.log("params", params.key);
});
const key = this.route.snapshot.params['key'];
console.log("key", key);

3.在路由配置中傳參(注意:可以用於自定義路由預加載)

路由路徑配置:

path: "news",
component: NewsComponent,
data: { key: "hero" }

獲取參數方法:

this.route.data.subscribe(params => {
  console.log("params", params.key);
});
const key = this.route.snapshot.params['key'];
console.log("key", key);

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章