2017-03-02 31 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

相关问题