一、navigate
函數定義:
navigate(commands: any[], extras?: NavigationExtras)
interface NavigationExtras { relativeTo? : ActivatedRoute queryParams? : Params fragment? : string preserveQueryParams? : boolean preserveFragment? : boolean skipLocationChange? : boolean
replaceUrl? : boolean }
使用
1. relativeTo
路由有以下幾種路徑 ./path, ../path, /path, path
| ./path | 這個表示當前路由 |
| ../path | 表示從當前route往上(parent),也可以使用../../path |
| /path | 表示從 root 開始,即根路由 |
| path | 表示從當前往下(child) |
默認為根路由,也可以修改為當前路由,修改過后以上那些path相對於當前路由進行導航;除了/path ,此為根路由
this._router.navigate(['/product'], {relativeTo:this.activeRouter})
需要說明的是,在模板中的routerLink中設置的path默認是當前路由(除了/path ,此為根路由),比如當前路由為http://localhost:4200/home
<a routerLink="a">跳轉到a</a> //跳轉后的路徑為http://localhost:4200/home/a
this._router.navigate(['/a'], {relativeTo:this.activeRouter}); //跳轉后的路徑為http://localhost:4200/a
this._router.navigate(['a'], {relativeTo:this.activeRouter}); //跳轉后的路徑為http://localhost:4200/home/a
注意:以下划線開頭的path,都是以根路由為參照,不管你設置的是什么
2.queryParams
// Navigate to /results?page=1 this.router.navigate(['/results'], { queryParams: { page: 1 } });
3.fragment
// Navigate to /results#top this.router.navigate(['/results'], { fragment: 'top' });
4.preserveQueryParams
// Preserve query params from /results?page=1 to /view?page=1 this.router.navigate(['/view'], { preserveQueryParams: true });
5.queryParamsHandling
// from /results?page=1 to /view?page=1&page=2 this.router.navigate(['/view'], { queryParams: { page: 2 }, queryParamsHandling: "merge" });
6.preserveFragment
// Preserve fragment from /results#top to /view#top this.router.navigate(['/view'], { preserveFragment: true });
7.skipLocationChange
// Navigate silently to /view this.router.navigate(['/view'], { skipLocationChange: true });
默認值為false,設為true路由跳轉時瀏覽器中的url會保持不變,但是傳入的參數依然有效
8.replaceUrl
// Navigate to /view this.router.navigate(['/view'], { replaceUrl: true });
未設置時默認為true,設置為false路由不會進行跳轉
