Angular2没有服务提供者 - 外部模块

时间:2017-03-02 09:19:04

标签: angular angular2-services

我构建了一个Angular Module,它拥有自己的服务和组件:

@NgModule({
  declarations: [ FileUploader],
  exports: [ FileUploader ],
  imports: [ CommonModule ],
  providers: [ FileService ],
})
export class FilesModule { }

FileService

import { Injectable } from '@angular/core';

@Injectable()
export class FileService
{
    constructor() {}

    uploadFile(file): Promise {
        return new Promise((resolve, reject) => {
            ...
        }
    }
}

然后我将其导入我的AppModule

@NgModule({
  declarations: [ AppComponent ],
  entryComponents: [ AppComponent ],
  imports: [ FilesModule ]
})
export class AppModule { }

当我将FileService注入AppComponent时,我收到错误:

AppComponent中的错误:没有FileService的提供程序

来自Angular docs:

  

当我们导入模块时,Angular会将模块的服务提供者(其提供者列表的内容)添加到应用程序根注入器。

     

这使得提供程序对应用程序中知道提供程序的查找标记的每个类都可见。

我缺少什么让这项工作?

2 个答案:

答案 0 :(得分:3)

当我的ForRoot中的提供者正在使用时,我总是创建NgModule方法:

@NgModule({
  declarations: [FileUploader],
  exports: [FileUploader],
  imports: [CommonModule]
})
export class FilesModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: FilesModule,
      providers: [
        FileService
      ]
    }
  }
}

然后,您可以在AppModule

中使用此功能
@NgModule({
  declarations: [AppComponent],
  entryComponents: [AppComponent],
  imports: [FilesModule.forRoot()]
})
export class AppModule {}

答案 1 :(得分:2)

我认为您尝试在AppComponent级别使用FileService。如果这样做,您应该将FileService添加到AppModule的提供程序或在FileModule级别使用FileService。

您可能忘记了FileService中的 @Injectable() anotation

相关问题