2017-03-02 32 views
3

我建立了一個角Module有它自己的服務和組件:Angular2沒有提供服務 - 外部模塊

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

當我注入FileServiceAppComponent我得到一個錯誤:

錯誤AppComponent:無提供的FileService

從角文檔:

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.

我缺少什麼,使這項工作?

+0

您是否在您的app.module.ts中導入FileService? – Pterrat

回答

1

我認爲你嘗試在AppComponent級別使用FileService。如果你這樣做,你應該添加FileService到AppModule的提供者或者在FileModule級別使用FileService。

可能的話,你忘了@Injectable() anotation在你的FileService

+1

我正在'FileModule'級別導入'FileService',我沒有忘記'@Injectable()' – naomi

+1

就是這樣!我有一個不同的文件,仍然從'AppModule'級別導入'FileService' - 我想知道爲什麼我在AppComponent **中有**錯誤,而不是在那個文件中。 – naomi

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 {} 
+0

我添加了'forRoot'方法,但仍然收到錯誤 – naomi

+0

,並且在'AppModule'導入中添加了'forRoot()'? – PierreDuc

+0

這正是我所做的 – naomi

相關問題