Angular4路由Router类中navigate跳转用法

网友投稿 2010 2022-05-29

之前通过学习 angular4 框架的开发,它确实比以前有了很大的变化和改进,好多地方也不是那么容易就能理解,好在官方的文档和例子是中文,示例相对简单,对英文不太好的伙伴们学习还是有很大帮助。

官方地址:https://angular.cn/

路由文档:https://angular.cn/api/router/Router#instance-methods

在学习的过程中首先要学习掌握框架的基础知识,接着就是路由(router)机制的学习,项目开发中路由是离不开的,且好多地方都要用到。

路由配置(Route)

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home.component'; import { LoginComponent } from './login.component'; import { RegisterComponent } from './register.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'heroes', component: RegisterComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule {}

路由跳转(Router.navigate)

navigate(commands: any[], extras?: NavigationExtras) : Promise

interface NavigationExtras { relativeTo : ActivatedRoute queryParams : Params fragment : string preserveQueryParams : boolean queryParamsHandling : QueryParamsHandling preserveFragment : boolean skipLocationChange : boolean replaceUrl : boolean }

其它属性和方法

根路由跳转(/login)

this.router.navigate(['login']);

设置relativeTo相对当前路由跳转,route是ActivatedRoute的实例,使用需要导入ActivatedRoute

this.router.navigate(['login', 1],{relativeTo: route});

路由中传参数(/login?name=1)

Angular4中路由Router类中navigate跳转用法

this.router.navigate(['login', 1],{ queryParams: { name: 1 } });

保留之前路由中的查询参数,将 preserveQueryParams 默认值为false,设为true,如(/login?name=1 to /home?name=1)

this.router.navigate(['home'], { preserveQueryParams: true });

路由中锚点跳转(/home#top)

this.router.navigate(['home'],{ fragment: 'top' });

保留之前路由中的锚点,将 preserveFragment 默认为false,设为true,如(/home#top to /role#top)

this.router.navigate(['/role'], { preserveFragment: true });

路由跳转时浏览器中的url会保持不变,但是传入的参数依然有效,将 skipLocationChange 默认为false,设为true

this.router.navigate(['/home'], { skipLocationChange: true });

路由不进行跳转,将 replaceUrl 默认为true,设为false

this.router.navigate(['/home'], { replaceUrl: true });

温馨提示

文章内容如果写的存在问题欢迎留言指出,让我们共同交流,共同探讨,共同进步~~~

文章如果对你有帮助,动动你的小手点个赞,鼓励一下,给我前行的动力。

Angular JavaScript

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:机房重构--验收总结
下一篇:【MATLAB】基本绘图 ( text 函数 | annotation 函数 | 绘制图像示例 )
相关文章