2017-05-04 27 views
0

返回角度js(使用ui-router)。你可以添加元數據到你的路線並使用路由變換中的元數據。角衛中的角度路由元數據

在角度上有這個衛兵,但我似乎無法弄清楚如何獲取元數據的路線定義。

爲了給你一個更具體的例子,我想能夠添加元數據到一個路線,讓我們說所需的角色和/或權限,並讓一名警衛完成重任。

路由定義:

RouterModule.forChild([ 
    { 
     path: '', 
     component: MyComponent, 
     data: { 
      permissions: ["view"], 
      roles: ["admin", "user"] 
     } 
    }, 
    ... 
]); 

然後在我的後衛:

constructor(private myService: MyService, private router: Router) {} 

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 
    //How to get a hold of the data defined for the current route ? 
    console.log(route.data); //returns an empty object 
} 

回答

1

route.data[ 'permissions' ][ 0 ]應在MyGuardcanActivate方法的字符串viewMyGuard應該執行CanActivate。你的路由應該看起來像這樣:

{ 
    path: '', 
    component: MyComponent, 
    data: { 
     permissions: ["view"], 
     roles: ["admin", "user"] 
    }, 
    canActivate: [ MyGuard ] 
} 

而且這個路由在訪問路由的根時應該工作。 A detailed explanation可以在官方網站上找到。

+0

後來我確實意識到我的警衛是在錯誤的路線定義上。不管怎麼說,還是要謝謝你 – RVandersteen