为什么我不能在@NgModule中导入Angular 2服务?

Tom*_*omR 2 javascript typescript angular

我有ExchangeServiceAngular 2 @Injectable类,并且有一个应用程序主模块:

@NgModule({
    imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,
        ExchangeService,
        RouterModule.forRoot(routes)
    ],
   providers: [
    {   provide: LocationStrategy,
        useClass: HashLocationStrategy
    },
    ExchangeService
   ]
...})
Run Code Online (Sandbox Code Playgroud)

引发异常

(index):16 Error: (SystemJS) Unexpected value 'ExchangeService' imported by the module 'Application5'
     Error: Unexpected value 'ExchangeService' imported by the module 'Application5'
     Error: (SystemJS) Unexpected value imported by the module Error: Unexpected value imported by the module
     Error: Unexpected value imported by the module at eval (http://127.0.0.1:8080/node_modules/@angular/compiler/bundles/compiler.umd.js:13982:37) at Array.forEach (native) at CompileMetadataResolver.getNgModuleMetadata 
     Error: Unexpected value imported by the module at eval at Array.forEach (native) at CompileMetadataResolver.getNgModuleMetadata 
Run Code Online (Sandbox Code Playgroud)

当我ExchangeServiceimports子句中删除(并且离开in providers子句)时,该异常消失。我(目前)不需要明确ExchnageService地在in imports子句中(我不知道它有什么好处),我只是想ExchangeService在全局组件中可用于其他服务的注入。

问题是- 为什么不允许写ExchangeServicein imports子句? Imports子句还包含其他TypeScript类-诸如此类HttpModule,为什么imports子句也不允许包含ExchangeService

Saj*_*ran 5

您应该在供应商内部导入

从......中去除

 imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,       
        RouterModule.forRoot(routes)
    ]
Run Code Online (Sandbox Code Playgroud)

imports:用于导入支持的模块,例如FormsModule,RouterModule,CommonModule或任何其他定制的功能模块。

读这个 what-is-difference-between-declarations-providers-and-import-in-ngmodule

  • 服务和模块是两件事 (2认同)