How do I set up global providers when using new feature that is NgModule? In the past I could do this:
bootstrap(AppComponent, [
GlobalServiceAAA,
GLOBAL_PROVIDERS_BBB
]);
Using NgModule we bootstrap the app int his way:
platformBrowserDynamic().bootstrapModule(AppModule);
where in this case I place my global services and providers (assuming I do not want to provide them in every component)?
You need to specify them within the providers attribute of your NgModule.
@NgModule({
(...)
providers: [ // <-------
GlobalServiceAAA, GLOBAL_PROVIDERS_BBB
]
})
export class AppModule { }
There are two ways to do it.
NOTE : Shared feature module may contain your common services.
1. without shared feature module
@NgModule({
(...)
providers: [ // <-------
GlobalServiceAAA, GLOBAL_PROVIDERS_BBB
]
})
export class AppModule { }
2. with shared feature module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {SharedModule} from './shared/shared.module'; //<-------- Important
...
...
@NgModule({
imports: [ BrowserModule,
SharedModule.forRoot(), //<----------Important
HomeModule,
routing
],
declarations: [ AppComponent],
bootstrap: [ AppComponent ]
})
export class AppModule { }
shared.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GlobalServiceAAA} from './path' //<-------- important
import { GLOBAL_PROVIDERS_BBB} from './path'; //<-------- important
@NgModule({
imports: [ CommonModule ],
declarations: [],
exports: [ CommonModule ]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [ GlobalServiceAAA,GLOBAL_PROVIDERS_BBB] //<------important
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With