路由navigate
一、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路由不会进行跳转