Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set global providers in Angular2 2.0.0 RC.5?

Tags:

angular

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)?

like image 943
Baumi Avatar asked Dec 05 '25 07:12

Baumi


2 Answers

You need to specify them within the providers attribute of your NgModule.

@NgModule({
  (...)
  providers: [ // <-------
    GlobalServiceAAA, GLOBAL_PROVIDERS_BBB
  ]
})
export class AppModule { }
like image 121
Thierry Templier Avatar answered Dec 07 '25 21:12

Thierry Templier


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
    };
  }
}
like image 31
Nikhil Shah Avatar answered Dec 07 '25 22:12

Nikhil Shah



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!