脚本宝典收集整理的这篇文章主要介绍了angular4学习记录 -- 路由,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
Angular4 路由
路由时传递数据
1.在查询参数中传递数据
/product?id=1&name=2 => ActivateRoute.queryParams[id]
2.在路由路径中传递数据
{path:/product/:id} => /product/1 => ActivateRoute.params[id]
3.在路由配置中传递数据
{path:product, component:ProductComponent, data:[{isProd:true}] => ActivatedRoute.data[0][isProd]
路由事件
事件
description
NavigationStart
事件开始时触发
RoutesRecognized
在解析完URL,并识别出了相应的路由时触发
RouteConfigLoadStart
在Router对一个路由配置进行惰性加载之前触发
RouteConfigLoadEnd
在Router被惰性加之后触发
NavigationEnd
导航成功之后触发
NavigationCancel
导航被取消之后触发。可能是因为导航期间某个路由守卫返回了false
NavigationError
在导航发生意外的错误时触发
子路由
语法:
const routes: Router = [
{ path: 'home', component: HomeComponent },
{ path: 'others', component: OthersComponent,
children: [
path: '', component: XxxComponent,
path: 'yyy', component: YyyComponent
]
},
]
辅助路由
- 在页面中设置路由插座:
<router-outlet name="aux"></router-outlet>
- 单独开发一个新组件,只显示在新定义的插座上。
- 通过设置路由参数,控制辅助路由的插座是否显示组件内容。
具体设置:{ path: 'consult', component: ConsultComponent, outlet: 'aux'}
路由守卫
在设置路由守卫时需先做下面两步:
一、在module
中添加providers
二、在routing.module
中添加需要守卫的路由的canActivate
、 canDeactivate
或者 Resolve
,前两个是数组形式,Resolve
是对象形式。
-
CanActivate:处理导航到某路由的情况
在guard文件中实现CanActivate
接口:
canActivate() {
var hasPermission:boolean = Math.random() < 0.5;
if(!hasPermission) {
console.log("用户无权访问次股票详情")
}
return hasPermission;
}
-
CanDeactivate:处理从当前路由离开的情况
在guard文件中实现CanDeActivate
接口:
canDeactivate(component: StockComponent){
if(component.isFocus()){
return true;
}else{
return window.confirm("关注一下哦。!")
}
}
-
Resolve:在路由激活之前获取路由数据
在guard文件中实现Resolve
接口
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any {
let id = route.params["id"];
if(id == 1){
return new Stock(1, "IBM");
}else {
this.router.navigate(['/home']);
return undefined;
}
}
以上是脚本宝典为你收集整理的angular4学习记录 -- 路由全部内容,希望文章能够帮你解决angular4学习记录 -- 路由所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。