Hi im new at angular 2 and Im trying to put in place all the things I have learned in angular.io. The problem is that I have readed about the core module, services, injectables ... and
If I have lets say a core-module like this:
import { NgModule } from '@angular/core';
import { LoggerService } from './services/logger.service';
@NgModule({
exports: [
//components
LoggerComponent,
],
declarations: [LoggerComponent],
providers: [LoggerService],
})
export class CoreModule { }
and a simple app.module like:
import { CoreModule } from './core/core.module';
import { AppComponent } from './app.component';
@NgModule({
imports: [
CoreModule,
BrowserModule,
HttpModule,
routerModule,
],
declarations: [
AppComponent,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
How can I use the LoggerService service exported for the core-module? i have to
import {LoggerService} from './core/services';
in my app.component? because in the contructor of app.component its not working
constructor(logger: LoggerService){}
what Im missing? thanks!
From the ngModule
documentation
providers : Provider[] Defines the set of injectable objects that are available in the injector of this module.
In other words, providers will be internal to the module and not outwardly exposed. Further reading in the documentation shows that only directives/pipes/(components) are applicable to export/declare.
So, to resolve this, you would need to directly reference the service in your higher level module, note that it will correctly use the singly instantiated service in your core module which is pretty cool and breaks my expectation.
app.module.ts
import {LoggerService} from './core/services';
@NgModule({<...>, providers: [<...>, LoggerService]})<...>
If you are going to have a bunch of shared services than using a barrel where you list all of them and do a one time import would be a reasonable approach.
Here's the functioning demo