3
votes

I have implemented lazy loading modules into my application, the app.module.ts is configured correctly.

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The routing configuration

const APP_ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { path: 'tools', loadChildren: 'app/tools/tools.module#ToolsModule' }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

Providing a service through the providers field in the child module and switching between components of that module reinstantiates that service (tested by logging in the service constructor).

The service is provided in the module only.

@NgModule({
  declarations: [
    ToolsComponent,
    ToolsCartComponent,
    ToolsContainerComponent,
    ToolsFormComponent
  ],
  imports: [
    CommonModule,
    toolsRouting
  ],
  providers: [ToolsService]
})
export class ToolsModule { }

Why isn't the provided service not a singleton?

EDIT:

I have modified a plunker example for lazy loading modules by adding a service scoped only to that module (backend module in this case). Switching between BackendComponent and BackendSecondComponent (which are both declared under the lazy loaded module) the service gets reinstantiated (visible in the console)

Plunker link

2
Having the same issue, I believe it is because the .forRoot() method is not called when lazy loading a module... I am looking for a similar solution, but I need my service to be a singleton.. .. .cheersSpock
Have similar problem. Each time I open route with lazy loaded module new service is created despite the fact that service provider is at the module level.mrh
I'm sure you already know the work-around for this (to provide the service in app module) Working plunker: plnkr.co/edit/UnxciqNLfL80BotWsYri?p=preview. One thing to note is that this warning: Angular2 Module documentation link In the doc it says "Do not specify app-wide singleton providers in a shared module. A lazy loaded module that imports that shared module will make its own copy of the service." It is related to this but I don't know the core reason.eko

2 Answers

0
votes
0
votes

I think this is the same problem as this Stackoverflow post: How do I provide a service in a lazy-loaded module and have that service scoped to just the lazy-loaded module and its components?

The solution was to create a "root component" in the lazy loaded module and add the components to this new root component.