Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 317
TomR Avatar asked Jan 22 '26 09:01

TomR


1 Answers

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

like image 61
Sajeetharan Avatar answered Jan 25 '26 07:01

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!