您好,欢迎访问一九零五行业门户网

Angular4中路由Router类的实例详解

最近一直在学习angular4,它确实比以前有了很大的变化和改进,好多地方也不是那么容易就能理解,好在官方的文档和例子是中文,对英文不太好的还是有很大帮助去学习。
官方地址:
在学习的过程中路由(router)机制是离不开的,并且好多地方都要用到。
首先路由配置route:
 1 import { ngmodule }             from '@angular/core'; 2 import { routermodule, routes } from '@angular/router'; 3   4 import { homecomponent }   from './home.component'; 5 import { logincomponent }      from './login.component'; 6 import { registercomponent }  from './register.component'; 7   8  const routes: routes = [ 9    { path: '', redirectto: '/home', pathmatch: 'full' },10    { path: 'home',  component: homecomponent },11    { path: 'login', component: logincomponent },12    { path: 'heroes',     component: registercomponent }13  ];14  15  @ngmodule({16    imports: [ routermodule.forroot(routes) ],17    exports: [ routermodule ]18  })19  export class approutingmodule {}
view code
其次路由跳转router.navigate
1 navigate(commands: any[], extras?: navigationextras) : promise<boolean>
1 interface navigationextras { 2     relativeto : activatedroute 3     queryparams : params 4     fragment : string 5     preservequeryparams : boolean 6     queryparamshandling : queryparamshandling 7     preservefragment : boolean 8     skiplocationchange : boolean 9     replaceurl : boolean10 }
view code
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 });
还有好多好多东西需要学习,关于跳转就先写到这里了,希望大家共同学习分享踏过的坑。
以上就是angular4中路由router类的实例详解的详细内容。
其它类似信息

推荐信息