当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 详解Angular4中路由Router类的跳转navigate

详解Angular4中路由Router类的跳转navigate

2017年12月12日  | 移动技术网IT编程  | 我要评论

最近一直在学习angular4,它确实比以前有了很大的变化和改进,好多地方也不是那么容易就能理解,好在官方的文档和例子是中文,对英文不太好的还是有很大帮助去学习。

官方地址:https://angular.cn/docs/ts/latest/api/router/index/router-class.html

在学习的过程中路由(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<boolean>
 interface navigationextras {
  relativeto : activatedroute
  queryparams : params
  fragment : string
  preservequeryparams : boolean
  queryparamshandling : queryparamshandling
  preservefragment : boolean
  skiplocationchange : boolean
  replaceurl : boolean
}

1.以根路由跳转/login

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

2.设置relativeto相对当前路由跳转,route是activatedroute的实例,使用需要导入activatedroute

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

3.路由中传参数 /login?name=1

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

4.preservequeryparams默认值为false,设为true,保留之前路由中的查询参数/login?name=1 to /home?name=1

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

5.路由中锚点跳转 /home#top

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

6.preservefragment默认为false,设为true,保留之前路由中的锚点/home#top to /role#top

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

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

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

8.replaceurl默认为true,设为false,路由不会进行跳转

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网