使用routerLink跳轉
- <a routerLink=["/exampledetail",id]></a>
- <a routerLink=["/exampledetail",{queryParams:object}] ></a>
使用navigate跳轉
import { Router } from '@angular/router';
- this.router.navigate(['user', 1]);
以根路由為起點跳轉 - this.router.navigate(['user', 1],{relativeTo: route});
默認值為根路由,設置后相對當前路由跳轉,route是ActivatedRoute的實例,使用需要導入ActivatedRoute - 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路由不會進行跳轉
獲取query方式的參數
import { ActivateRoute } from '@angular/router'; public id: any; snapshot constructor( public activeRoute: ActivateRoute ) { }; ngOnInit(){ this.id= this.activeRoute.snapshot.params['id']; }; queryParams ngOnInit(){ this.activeRoute.queryParams.subscribe(params => { this.id = params['id']; });