1

i create a service and i want to share the data inside this service so i found in some tutorial that i have to bootstrap the service in the appmodule of my application to make sure that is only one instance of this service :

@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,


  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService,SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent,[SessionService]]
})
export class AppModule { }

i make the SessionService in the boostrap but i have an error in the browser console :

zone.js:522 Unhandled Promise rejection: Component SessionService is not part of any NgModule or the module has not been imported into your module. ; Zone: ; Task: Promise.then ; Value: ZoneAwareError {__zone_symbol__error: Error: Component SessionService is not part of any NgModule or the module has not been imported into……} Error: Component SessionService is not part of any NgModule or the module has not been imported into your module.

this is my main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
Yassine CHABLI
  • 3,459
  • 2
  • 23
  • 43

1 Answers1

0

I think your tutorial is from a beta version.

because before the r.c version, the notation was like

bootstrap(AppComponent, [provide(SharedService, {useValue: sharedService})]);

Now if you want to provide a service globally as a singleton, all you have to do is to provide it inside the providers array in your root module.

@NgModule({
  declarations: [
    AppComponent,
    ProfileComponent,
    TestComponent,


  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    SlimLoadingBarModule.forRoot(),
    FormWizardModule

  ],
  exports: [BrowserModule, SlimLoadingBarModule],
  providers: [UserResolverService, SessionService,  appRoutingProviders ],
  bootstrap: [AppComponent] //<---- remove it from here
})
export class AppModule { }
eko
  • 39,722
  • 10
  • 72
  • 98
  • how to make shure that i have only one instance ? – Yassine CHABLI Jun 07 '17 at 05:56
  • @MOHAMMEDYASSINEChabli if you provide that service in a higher level than your component, it will be a singleton (one instance). Check: https://stackoverflow.com/questions/43997489/angular-shared-service-between-components-doesnt-work. So if you provide this service **only** in your app module, it will only have one instance in your app. – eko Jun 07 '17 at 05:58