[英]Angular2 - Invalid provider error when injecting service into service
我目前有一个如下所示的模块设置(摘录);
AppModule
RoutingModule
AuthRouteGuard
AuthModule
LoginFormComponent
AuthService
我已经定义我AuthService
(负责处理用户认证和提供了用于确定当前用户是否被认证的方法),其在我的供应商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 { }
将authHttpServiceProvider
添加到模块的导入中。 它已导出到全局,无法用于模块。 因此,由于模块的提供者未知,因此无法提供服务。
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule
],
exports: [AuthComponent],
declarations: [AuthComponent, LoginComponent, RegisterComponent],
providers: [
AuthService
]
})
export class AuthModule {
实际问题出在AuthService
本身内。
AuthModule
定义了一个常量;
export const jwtKey = 'jwt';
将其导入到AuthService
并使用;
import { jwtKey } from '../auth.module';
由于某种原因,如果我删除此导入,一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.