我目前有一个如下所示的模块设置(摘录);
AppModule
RoutingModule
AuthRouteGuard
AuthModule
LoginFormComponent
AuthService
我已将 my AuthService
(负责处理用户身份验证并提供确定当前用户是否经过身份验证的方法)定义为 my 中的提供程序AuthModule
;
// auth.module.ts - uses https://github.com/auth0/angular2-jwt
export function authHttpServiceFactory(http: Http, options: RequestOptions) {
return new AuthHttp(new AuthConfig({
tokenName: jwtLocalStorageKey
}), http, options);
}
export let authHttpServiceProvider = {
provide: AuthHttp,
useFactory: authHttpServiceFactory,
deps: [Http, RequestOptions]
};
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService,
authHttpServiceProvider
]
})
export class AuthModule { }
我可以在其同级中毫无问题地使用此服务LoginFormComponent
。但是,当我尝试AuthService
在AuthRouteGuard
类中使用RoutingModule
时,出现以下错误;
Error: Invalid provider for the NgModule 'AuthModule' - only instances of Provider and Type are allowed, got: [?undefined?, ...]
我AuthModule
在RoutingModule
. 一旦AuthService
被定义为AuthRouteGuard
;的依赖项,就会发生上述错误。
export class AuthRouteGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService // Removing this injection removes the error
) {}
canActivate() {
// @todo: if not authenticated
this.router.navigate(['/login']);
return true;
}
}
我在这里遗漏了什么,为什么在构造函数中注入服务会导致无效的提供程序错误,而该错误在删除该注入时不会发生?
编辑authHttpServiceProvider
- 如果完全删除提供程序,则会发生相同的错误,因此AuthModule
模块看起来像;
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule { }