2016-06-29 64 views
0

我做的基于令牌的认证为我angular2应用程序,我一直在使用最新的RC3路由器在x.routes.ts无提供服务

干过这是我在site.routes.ts代码文件

import {Authentication} from './authenticaton.service'; 
import { RouterConfig,CanActivate } from '@angular/router'; 
import { SiteComponent} from './site.component'; 
import { LoginComponent } from './login.component'; 
import { ProfileComponent } from './profile.component'; 
export const SITE_ROUTES: RouterConfig = [ 
    { 
    path: '', 
    component: SiteComponent, 
    children: [ 
     { 
     path: 'login', 
     component: LoginComponent 
     }, 
     { 
     path: 'profile', 
     component: ProfileComponent, 
     canActivate: [Authentication] 
     } 
    ] 
    } 
]; 

在编译时没有错误,但当我尝试访问配置文件路由时,它在控制台中给了我这个错误。

没有认证的提供者!

我试图给认证的供应商,但装饰不是在x.routes.ts文件

这里支持我的authentication.service.ts文件

import { Injectable } from '@angular/core'; 
import { CanActivate,Router,ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router'; 
import { AuthService } from './auth.service'; 

@Injectable() 
export class Authentication implements CanActivate { 
    constructor(private authService: AuthService, private router: Router) {} 

    canActivate(
    // Not using but worth knowing about 
    next: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot 
) { 
    if (this.authService.isLoggedIn) { return true; } 
    this.router.navigate(['/login']); 
    return false; 
    } 
} 
+0

您是否在'ProfileComponent'中提供了'Authentication'。或者你在'AuthGuard'中使用'Authentication'? – Dinistro

+0

我做了编辑,请再次检查。 –

+0

你可以添加'Authentication'的代码吗? – Dinistro

回答

1

尝试与路由器添加常量提供者在site.routes.ts:

export const APP_ROUTER_PROVIDERS = [ 
    provideRouter(SITE_ROUTES), 
    Authentication 
]; 

而不是将APP_ROUTER_PROVIDERS添加到您的引导功能。

import { APP_ROUTER_PROVIDERS } from 'site.routes.ts'; 


    bootstrap(AppComponent, [ 
     ... 
     APP_ROUTER_PROVIDERS 
     ... 
    ] 
+0

有一个问题,我已经使用isLoggedIn位,现在工作正常。 –