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;
             }
        }
相關文章
相關標籤/搜索