NullInjectorError:没有“ConfigService”的提供者

时间:2018-03-01 21:22:37

标签: angular typescript dependency-injection

我有2个模块 ConfigModule LoginModule ,每个模块都有一个服务 ConfigService LoginService LoginService 使用 ConfigService

我的 LoginModule

 @NgModule({
   imports: [
     // Angular
     CommonModule,
     HttpClientModule,
     BrowserAnimationsModule,
     FormsModule,
     // Angular Material Flex Layout
     FlexLayoutModule,
     // Angular Material
     MatInputModule,
     MatButtonModule,
     MatIconModule
   ],
   declarations: [
     // Components
     LoginComponent,
     NewUserComponent,
     ForgotPasswordComponent,
     // Directives
     ForbiddenCharactersDirective,
     EquateDirective
   ],
   providers: [
     { // this will activate when you include this module
       provide: HTTP_INTERCEPTORS,
       useClass: AuthHttpInterceptor,
       multi: true
     },
     LoginService
   ],
   schemas: [ NO_ERRORS_SCHEMA ],
   exports: [
     LoginComponent,
     NewUserComponent,
     ForgotPasswordComponent,
     ForbiddenCharactersDirective,
     EquateDirective
   ]
 })

我的 ConfigModule

 @NgModule({
   imports: [
     CommonModule,
     HttpClientModule
   ],
   providers: [
     ConfigService,
     {
       provide: APP_INITIALIZER,
       useFactory: initConfig,
       deps: [ConfigService],
       multi: true
     }
   ]
 })

LoginService 的构造函数

 constructor(
   private _http: HttpClient,
   private _configSrvc: ConfigService // <==== Injected ConfigService
 ) {
  // get base url for api endpoints
  let api = this._configSrvc.get('api');
  if(api && (typeof api === 'string'))
    this.baseUrl = api;

  let endpoints = this._configSrvc.get('login.endpoints');
  if(endpoints)
    this._endpoints.endpoints = endpoints;
} // constructor

当我将两个模块导入我的应用程序模块时

 @NgModule({
   imports: [
     ...,
     ConfigModule,
     LoginModule
   ]
 })

然后尝试运行ng serveng serve --preserve-symlinks我收到以下错误

 AppComponent.html:2 ERROR Error: StaticInjectorError(AppModule)[LoginService -> ConfigService]: 
   StaticInjectorError(Platform: core)[LoginService -> ConfigService]: 
     NullInjectorError: No provider for ConfigService!

据我了解,如果提供程序在导入模块的providers数组中声明,则提供程序应该可用于整个应用程序,而它是其他模块/组件/ etc。

我不明白为什么 LoginService No provider for ConfigService

我唯一能想到的是,在 ConfigService 同时或之前实例化 LoginService 的情况下会出现一些竞争情况,但我该如何修复如果那是罪魁祸首?

0 个答案:

没有答案