'错误没有提供TokenGuard'将子路由添加到保护路由时

时间:2018-01-04 10:18:24

标签: angular angular2-routing

我创建了一个有角度的2 / web api应用程序,其中我有一个Startpage,用户不必登录,这与应用程序的其他部分不同。 此设置适用于Startpage组件,但现在我想向路由模块添加子路由messages,突然我在控制台中看到以下错误消息:Error: no provider for TokenGuard。 这是我的路由模块的内容

const routes: Routes = [
{
    path: '',
    component: MainComponent,
    children: [
        {
            path: '',
            component: MainNavigationComponent,
            children: [
                {
                    path: 'messages',
                    component: MessagesComponent,
                    resolve: { connection: ConnectionResolver }
                },
                {
                    path: 'todos',
                    component: TodosComponent,
                    resolve: { connection: ConnectionResolver }
                },
                {
                    path: 'startpage',
                    canActivate: [TokenGuard],
                    canActivateChild: [TokenGuard],
                    component: StartpageComponent,
                    children: [
                        {
                            path: 'messages',
                            component: MessagesComponent
                        }
                    ]
                }
            ]
        }
    ]
}];

TokenGuard

import {StartpageService} from 'startpage.service';
import {Injectable} from '@angular/core';
import {CanActivate, Router,ActivatedRouteSnapshot, RouterStateSnapshot, CanActivateChild} from '@angular/router';

@Injectable()
export class TokenGuard implements CanActivate, CanActivateChild {
constructor(
    private startPageService: StartpageService,
    private router: Router
) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.startPageService.validateToken();
}

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

1 个答案:

答案 0 :(得分:0)

将TokenGuard添加到app.module提供程序

@NgModule({
  .....,
  providers:[..., TokenGuard]
})