2017-02-26 42 views
2

我試圖建立一個孩子後衛像角DOC:兒童後衛:canActivateChild不工作

@Injectable() 
export class AuthGuardService implements CanActivate, CanActivateChild { 

    constructor(private authService: AuthentificationService, private router: Router) {} 

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    let url: string = state.url; 

    return this.checkLogin(url); 
    } 

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { 
    return this.canActivate(route, state); 
    } 

    checkLogin(url: string): boolean { 
    /*****/ 
    return false; 
    } 
} 

我routing.module:

import { AuthGuardService } from '../services/auth-guard.service'; 

const routes = [ 
    { 
     path: '', 
     component: MyComponent, 
     canActivate: [AuthGuardService], 
     children: [{ 
      path: '', 
      canActivateChild: [AuthGuardService], 
      children: [ 
       { 
        path: 'candidature', 
        component: ListCandidatureComponent, 
       }, 
       { 
        path: 'candidature/new', 
        component: NewCandidatureComponent 
       }] 
     }, { 
      path: 'login', 
      component: LoginComponent, 

     }] 
    } 
] 

我把我的canActivateChild後衛組件通過認證來防止這種路由。

但有了這個配置,當我試圖達到「my.site.com/candidature」我得到這個錯誤:

Unhandled Promise rejection: guard is not a function ; Zone: angular ; Task: Promise.then ; Value: TypeError: guard is not a function 

通常情況下,如果我不authentitcated,我需要重定向到登錄頁面。 有人得到這個錯誤,或知道爲什麼它是午餐?

感謝的

回答

2

如果找到我的解決方案。我向其他有同樣問題的人解釋。

像例外情況一樣,路由模塊是子路由模塊的事實啓動此錯誤。我需要在AppRouting中提供AuthGuardService以用於像這樣的子路由模塊:

@NgModule({ 
    imports: [ 
     RouterModule.forRoot(routes) 
    ], 
    exports: [RouterModule], 
    declarations: [], 
    providers: [AuthGuardService] //Here add the AuthGuardService to be available in route-module-child 
}) 
export class AppRoutingModule {} 
3

canActivateChild: [AuthGuardService],不應該是裏面children,但在父路由聲明。

不確定的是,當您在孩子的內部聲明孩子時,還需要在外層孩子中聲明canActivateChild。但是你可以在沒有它的情況下進行測試。讓我知道它是否有效!

const routes = [ 
    { 
     path: '', 
     component: MyComponent, 
     canActivate: [AuthGuardService], 
     canActivateChild: [AuthGuardService] // it should be placed here! 
     children: [{ 
      path: '', 
      // canActivateChild: [AuthGuardService], // needed or not? 
      children: [ 
       { 
        path: 'candidature', 
        component: ListCandidatureComponent, 
       }, 
       { 
        path: 'candidature/new', 
        component: NewCandidatureComponent 
       }] 
     }, { 
      path: 'login', 
      component: LoginComponent, 

     }] 
    } 
] 

希望這有助於!