EDIT :显然这已经过时了,现在你在NgModule中的providers
数组中提供你的保护。有关更多信息,请查看其他答案或官方文档。
组件is outdated
provideRouter()
上的我正在尝试使用Angular2指南https://angular.io/docs/ts/latest/guide/router.html中的登录名和AuthGuard在我的项目中设置身份验证
我使用的版本是:"@angular/router":"3.0.0-beta.1“。
我会尽可能多地解释,如果你需要更多细节,请随时告诉我。
我有我的main.ts文件,它用以下代码引导应用程序:
bootstrap(MasterComponent, [
APP_ROUTER_PROVIDERS,
MenuService
])
.catch(err => console.error(err));
我加载了MasterComponent,它加载了一个标题,其中包含允许我在应用程序中导航的按钮,目前它还包含我的main。
我正在遵循这个指南,用下面的app.routes.ts让我的应用程序以同样的方式工作:
export const routes: RouterConfig = [
...LoginRoutes,
...MasterRoutes
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes),
AUTH_PROVIDERS
];
以及指南中定义我的AuthGuard的login.routes.ts:
export const LoginRoutes = [
{ path: 'login', component: LoginComponent }
];
export const AUTH_PROVIDERS = [AuthGuard, AuthService];
我的Master组件有它自己的路由定义,它还包含我正在尝试设置的防护。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)时,我得到了No provider for AuthGuard!错误。
我最近看到了与我的问题相同的帖子(NoProviderError using CanActivate in Angular 2),但对我来说,守卫是正确引导到main.ts文件的,所以我的路由器应该知道哪些路由应该与AuthGuard一起提供,对吗?
任何帮助或建议都将不胜感激。谢谢!
发布于 2016-07-05 22:08:42
实际上,这只是一个输入错误...
我在打字
从‘./../Authentification/auth.Guard’导入{ AuthGuard };
而不是
从‘./../authentification/auth.Guard’导入{ AuthGuard };
使其无法工作,但同时不显示任何错误...
(悲伤的脸)
发布于 2016-10-21 23:19:50
在阅读了Angular网站https://angular.io/docs/ts/latest/guide/router.html上的路由和授权教程的Route Guard部分后,我也遇到了同样的问题,它是第5部分。
我将AuthGuard添加到我的一个主路由中,而不是像本教程所示的子路由中。
我通过将AuthGuard添加到我的app.module.ts文件的提供程序列表中来修复它,因此该文件现在看起来如下所示:
import { AppComponent } from './app.component';
import {AppRoutingModule} from './app-routing.module';
import {AuthGuard} from './auth-gaurd.service';
import { AnotherPageComponent } from './another-page/another-page.component';
import { LoginPageComponent } from './login-page/login-page.component';
@NgModule({
imports: [
BrowserModule,
FormsModule,
JsonpModule,
AppRoutingModule,
HttpModule
],
declarations: [
AppComponent,
LoginPageComponent,
AnotherPageComponent
],
providers: [AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
我已经回顾了教程,在他们的app.module.ts文件中,他们没有将AuthGuard添加到提供程序中,不确定为什么。
发布于 2018-12-10 23:37:56
尝试添加
@Injectable({ providedIn: 'root' })
不需要添加到模块提供程序。
https://stackoverflow.com/questions/38203647
复制相似问题