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

标签 angular angular2-services

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

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

文件服务:

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 注入(inject)到 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.

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

最佳答案

当提供者在我的 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 {}

关于Angular2 没有服务提供者 - 外部模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42551248/

相关文章:

Angular 5 Promise 返回未定义

javascript - VM1052 :19 Error: (SystemJS) TypeScript transpilation failed

javascript - 在某些路线上隐藏标题组件(Angular 5)

java - 注释 @CrossOrigin ("*") 不起作用

javascript - AngularJs 2 : How to debug a service call?(es6 语法)

Angular 4 : how to pass an argument to a Service provided in a module file

javascript - 使用 Observables 时处理服务器错误

angular - 'ion-title' 不是已知元素 : while creating components on the fly

Angular 2 : Best Practice for Data Layer

angular - 在 Angular 2 的多个组件中全局保存和访问值