我目前有一個模塊設置,如下所示(exerpt);Angular2 - 將服務注入服務時無效的提供程序錯誤
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
內沒問題。當我嘗試在RoutingModule
的AuthRouteGuard
類中嘗試使用AuthService
但是,我收到以下錯誤;
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 { }
'AuthModule'是延遲加載模塊? –
否@BougarfaouiElhoucine,只是一個常規模塊 –