2017-02-13 21 views
0

Angular2路由中的警衛按其提供的順序運行。 但是在有守衛者的情況下,即使第一個守衛是真實的,角度也會忽略它,並且只應用第二守衛的可觀察結果。如果至少有一名警衛處於活動狀態,則轉到路線

我該如何解決這個問題?

const mainRoutes: Routes = [ 
    { 
    path: 'app', 
    component:MainComponent, 
    canActivate:[AuthGuard], 
    children:[ 
    { path: 'dashboard', component: DashboardComponent }, 
    { path: 'protectedRoute', component: ProtectedRouteComponent, canActivate:[Admin1Guard,Admin2Guard] } 
    ]} 
]; 

第1保護:

canActivate() :Observable<boolean>{ 
    return this.authService.getUser().map(res=>{ 
     if(res.user.role=="admin1") 
      return true; 
     }).take(1); 
    } 
} 

第二後衛:

canActivate() :Observable<boolean>{ 
    return this.authService.getUser().map(res=>{ 
     if(res.user.role=="admin2") 
      return true; 
     }).take(1); 
    } 
    } 
+0

聽起來像是正常的行爲。如果**至少有一個警衛返回false,那麼'canActivate'屬性將阻止用戶訪問該路線。所以在你的情況下,如果'Admin1Guard'返回true並且'Admin2Guard'返回false,則不應該授予訪問權限。您顯示的代碼是真實的代碼嗎?爲什麼你需要兩個可觀測物來測試同一個屬性? – AngularChef

+0

嗯,如果其中至少有一個是真的(守衛之間的OR關係),我想要路由。 我在應用程序中有很多角色,每個角色都可以訪問某些部分(當然也有部分可以被許多角色訪問),這就是爲什麼我爲每個角色創建了一個警衛。 有沒有更好的方法來做到這一點? –

回答

2

我會重構檢查角色的邏輯爲單一,通用CheckRoleGuard服務和附加名通過data屬性查詢路線的作用:

{ 
    path: 'protectedRoute1', 
    component: SomeComponent, 
    canActivate: [CheckRoleGuard], 
    data: { allowedRoles: ['admin','editor'] } 
}, 
{ 
    path: 'protectedRoute2', 
    component: SomeComponent, 
    canActivate: [CheckRoleGuard], 
    data: { allowedRoles: ['admin'] } 
} 

而現在的中RoleGuard服務:

@Injectable() 
class CheckRoleGuard { 

    constructor(private authService: AuthService) { } 

    canActivate(route: ActivatedRouteSnapshot): Observable<boolean> { 
    // Retrieve the allowed roles from `route.data`. 
    const allowedRoles = route.data['allowedRoles']; 

    return this.authService.getUser() 
     .map(data => { 
     return allowedRoles.indexOf(data.user.role) !== -1; 
     }); 
    } 

} 
+0

你是對的,最好是這樣做,但你的答案需要一些小的修正(我在編輯中做了修改,等待它的批准) –

+1

當然,謝謝。 :) – AngularChef

+0

我已經根據您的編輯添加了其他一些小改進(例如注入'AuthService')。這個代碼中'.take(1)'的用法是什麼? – AngularChef

相關問題