6
votes

I built an Angular Module that has it's own service and components:

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

And the FileService:

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

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

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

then I import it to my AppModule:

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

When I inject the FileService to the AppComponent I get an ERROR:

Error in AppComponent: No Provider for FileService

From Angular docs:

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.

What am I missing to make this work?

2
do you import FileService in your app.module.ts? - Pterrat

2 Answers

2
votes

I think that you trying use FileService at AppComponent level. If you do that you should add FileService to AppModule's providers or using FileService at FileModule level.

Possibly, you forget about @Injectable() anotation in your FileService

4
votes

I always create a ForRoot method when providers are in play in my NgModule:

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

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

You can then use this in your AppModule:

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