路由设置
Angular中路由的配置应该按照 先具体路由 到 通用路由 的设置,因为Angular使用 先匹配者优先 的原则。
示例: 路由设置如下:
export const reportRoute: Routes = [ { path: ' report ' , children: [ { path: '' , component: ReportComponent },{ path: ' :id ' , component: ReportDetailComponent },{ path: ' report-new ' , component: ReportNewComponent } ] } ];
在report页面,点击其上的创建按钮想要进入report-new页面,然而却报下面的错误:
原来路由先匹配到了report/:id这个路由,它把report-new当成了id参数进入了report-detail页面去获取report的detail去了。
将路由改成下面这样就OK了
export const reportRoute: Routes = [ { path: ' report ' , children: [ { path: '' , component: ReportComponent },{ path: ' report-new ' , component: ReportNewComponent },{ path: ' :id ' , component: ReportDetailComponent } ] } ];
路由处理流程
Angular2对待一个URL的处理流程为:
应用重定向 识别路由状态 应用哨兵与传递数据:哨兵的作用是判断是否允许应用在不同状态间进行切换 激活对应组件路由链接激活状态
<a routerLink= " /heroes " routerLinkActive= " active " >Heroes</a>
通过为链接设置属性 routerLinkActive="active"可以让路由链接保持为激活状态,当路由被激活时,会动态绑定一个active的class,通过设置类active的样式即可设置激活路由链接的样式。RouterLinkActive指令会基于当前的RouterState对象来为激活的RouterLink切换CSS类。这会一直沿着路由树往下进行级联处理,所以子路由和父路由链接可能会同时激活。
要改变这种行为,可以把[routerLinkActiveOptions]绑定到{exact: true}表达式。如果使用了{exact: true},那么只有在其URL与当前URL精确匹配时才会激活指定的RouterLink。
路由守卫
CanActivate:用来判断是否允许进入该状态,这个服务类需要继承CanActivate接口,实现canActivate方法
CanActivateChild
CanDeactivate
Resolve:在进入该状态前获取除当前路由参数之外的其他信息,数据分发器是一个service需要继承DataResolver接口,实现resolve方法,还需要把这个数据分发器加入到module的Providers中。
CanLoad
路由传参
路由跳转时使用navigate传参
单个参数:this.router.navigate(['/reports', report.id]); 多个参数:this.router.navigate(['/reports', {id: report.id, type: ' PATIENT_CASE '}]);在链接参数数组中,路由器支持“目录式”语法来指导我们如何查询路由名:
/,从根路径开始, ./或无前导斜线形式,相对于当前路径, ,从当前路径的上一级开始
查看更多关于Angular2 Router路由相关的详细内容...