TomR TomR - 14 days ago 9
Javascript Question

Why I cannot import Angular 2 service in @NgModule?

I have

ExchangeService
Angular 2
@Injectable
class and I have an application main module:

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


which raises Exception

(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


The exception disappears when I remove
ExchangeService
from the
imports
clause (and I leave in
providers
clause). I don't (at present) explicitly need
ExchnageService
to be in
imports
clause (I don't know what are benefits of it), I just want
ExchangeService
to be available for injection in other services in components globally.

The question is - why I am not allowed write
ExchangeService
in
imports
clause?
Imports
clause contains other TypeScript classes as well - like
HttpModule
and so on and why
imports
clause is not allowed to contain
ExchangeService
as well?

Answer

You should import inside providers

Remove from

 imports: [
        BrowserModule,
        HttpModule,
        FormsModule,
        ReactiveFormsModule,       
        RouterModule.forRoot(routes)
    ]

imports: is used to import supporting modules likes FormsModule, RouterModule, CommonModule, or any other custom-made feature module.

Read this what-is-difference-between-declarations-providers-and-import-in-ngmodule