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

nao*_*omi 6 angular2-services angular

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

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

FileService

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

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

    uploadFile(file): Promise {
        return new Promise((resolve, reject) => {
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我将它导入到我的AppModule

@NgModule({
  declarations: [ AppComponent ],
  entryComponents: [ AppComponent ],
  imports: [ FilesModule ]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

当我注入FileServiceAppComponent我得到一个错误:

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

来自 Angular 文档:

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

这使得提供者对应用程序中知道提供者的查找令牌的每个类都是可见的。

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

Jar*_* K. 2

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

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