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

Angular2 No provider for service - external module

我构建了一个 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 错误:没有文件服务提供程序

来自 Angular 文档:

When we import a module, Angular adds the module's service providers (the contents of its providers list) to the application root injector.

This makes the provider visible to every class in the application that knows the provider's lookup token.

我缺少什么来完成这项工作?

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

可能,您忘记了文件服务中的 @Injectable() 注释

当供应商在我的 NgModule 中发挥作用时,我总是创建一个 ForRoot 方法:

@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 {}