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
        ]
    },
]

辅助路由

  1. 在页面中设置路由插座:<router-outlet name="aux"></router-outlet>
  2. 单独开发一个新组件,只显示在新定义的插座上。
  3. 经过设置路由参数,控制辅助路由的插座是否显示组件内容。

具体设置:{ path: 'consult', component: ConsultComponent, outlet: 'aux'}dom

路由守卫

在设置路由守卫时需先作下面两步:ide

1、在 module中添加 providers
2、在 routing.module中添加须要守卫的路由的 canActivatecanDeactivate 或者 Resolve,前两个是数组形式, Resolve是对象形式。
  1. CanActivate:处理导航到某路由的状况
    在guard文件中实现CanActivate接口:this

    canActivate() {
         var hasPermission:boolean = Math.random() < 0.5;
         if(!hasPermission) {
           console.log("用户无权访问次股票详情")
         }
         return hasPermission;
     }
  2. CanDeactivate:处理从当前路由离开的状况
    在guard文件中实现CanDeActivate接口:code

    canDeactivate(component: StockComponent){
         if(component.isFocus()){
           return true;
         }else{
           return window.confirm("关注一下哦。!")
         }
     }
  3. Resolve:在路由激活以前获取路由数据
    在guard文件中实现Resolve接口component

    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;
             }
        }
相关文章
相关标签/搜索