【发布时间】:2016-11-07 07:16:48
【问题描述】:
编辑:显然这已经过时了,现在你在 NgModule 中的 providers 数组中提供保护。观看其他答案或官方文档以了解更多信息。
- 组件上的引导已过时
-
provideRouter()也已过时
我正在尝试使用 Angular2 指南中的登录名和 AuthGuard 在我的项目中设置身份验证:https://angular.io/docs/ts/latest/guide/router.html
我正在使用版本:“@angular/router”:“3.0.0-beta.1”。
我会尽量解释清楚,如果您需要更多详细信息,请随时告诉我。
我有我的 main.ts 文件,它使用以下代码引导应用程序:
bootstrap(MasterComponent, [
APP_ROUTER_PROVIDERS,
MenuService
])
.catch(err => console.error(err));
我加载了 MasterComponent,它加载了一个 Header,其中包含允许我浏览我的应用程序的按钮,并且它现在还包含我的 main。
我正在按照指南使我的应用程序以相同的方式工作,使用以下 app.routes.ts:
export const routes: RouterConfig = [
...LoginRoutes,
...MasterRoutes
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AUTH_PROVIDERS
];
以及指南中的 login.routes.ts,它定义了我的 AuthGuard:
export const LoginRoutes = [
{ path: 'login', component: LoginComponent }
];
export const AUTH_PROVIDERS = [AuthGuard, AuthService];
我的主组件有自己的路由定义,其中还包含我要设置的守卫。 master.routes.ts:
export const MasterRoutes : RouterConfig = [
{ path: '', redirectTo: '/accueil', pathMatch: 'full' },
{
path: 'accueil',
component: AccueilComponent
},
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
我使用与指南相同的文件,即 auth.guard.ts、auth.service.ts、login.component。 ts 和 login.routes.ts。
在我的 header.component.ts 文件中,当我尝试访问任何路由时,它工作得很好,但是当我尝试访问受保护的路径(/dashboard)时,我得到 没有 AuthGuard 提供程序! 错误。
我看到最近的帖子与我 (NoProviderError using CanActivate in Angular 2) 的问题相同,但对我来说,守卫被正确引导到 main.ts 文件,所以我的路由器应该知道哪些路由应该提供AuthGuard吧?
任何帮助或建议将不胜感激。 谢谢!
【问题讨论】:
-
您是否将
AuthGuard导入master.routes.ts和login.routes.ts? -
是的,我确实正确导入了它们。我没有提到它,但我手动导航到该路线,因为我想使用 this.router.navigate(['/dashboard']); 链接一个
-
奇怪的是我公司的防火墙实际上阻止了 plunkr 链接,所以我可能需要一点时间......我希望用一个正常工作的 plunkr 编辑此评论
-
不客气。很高兴听到你想通了。
标签: authentication angular angular2-routing