Angular 2 module that is loaded lazily - service does not follow singleton pattern

After successfully implementing lazy loading modules into my application, I have ensured that the app.module.ts is properly configured.

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

The routing setup

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

export const routing = RouterModule.forRoot(APP_ROUTES);

One observation is that providing a service through the providers field in the child module and switching between components of that module causes the service to be reinstantiated (confirmed through logging in the service constructor).

The service is only provided within the module.

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

I am puzzled as to why the provided service is not functioning as a singleton.

UPDATE:

Addition to the discussion, I have enhanced a plunker example for lazy loading modules by introducing a service scoped solely to that module (specifically in the backend module). Upon toggling between BackendComponent and BackendSecondComponent (both declared under the lazily loaded module), it is observed that the service undergoes re-instantiation (evident in the console)

Link to Plunker

Answer №2

It seems like the issue at hand mirrors that of a previously discussed problem on Stackoverflow: How can I ensure a service in a lazy-loaded module is scoped only to the module and its components?

The resolution involved creating a "root component" within the lazy loaded module and incorporating the components into this newly created root component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to reset an Angular 7 reactive form to its initial values instead of clearing them completely

Is there a way to restore a reactive form group back to its original values without completely clearing it using .reset()? In this StackBlitz example, the default selected value is Parent. If a user changes it to "sister" and wants to revert the form to i ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

Is there a way to launch Visual Studio Code using a web browser?

Is there a way to launch "Visual Studio Code" automatically upon clicking a button on my website? ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...

Create a visual representation of an image by sketching a detailed line profile using HTML5's

I am attempting to create an intensity profile for an image, using the x-axis as the line's length on the image and the y-axis as the intensity values along the length of the line. How can I achieve this on an HTML5 canvas? I have tried the code below ...

Instructions for adding the more-vert icon from material-ui into a react project

I've been searching tirelessly, but I can't seem to locate it. Where exactly is the location of this in material-ui? I've seen others using it. Any assistance would be greatly appreciated. My initial thought was: import MoreVertIcon from & ...

What is the best way to validate the Click outside directive in Angular applications?

Exploring the click-outside directive for testing purposes. It seems that there is an issue with ignoring a specific div element while clicking outside. import { Directive, ElementRef, Output, EventEmitter, HostListener } from '@angular/core'; ...

Create a unique onblur event listener for every element in a loop in Javascript

I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert, and if the length of the NRIC fi ...

The request does not include the cookies

My ReactJS client sends a cookie using this NodeJS code snippet: res.cookie("token", jwtCreation, { maxAge: 24 * 60 * 60 * 1000, // Milliseconds (24 hours) sameSite: 'None', // Cross-site requests allowed for modern browser ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...

What is the best way to keep only the arrow controls visible in TransformControls translation mode?

Currently, I am using TransformControls which meets my requirements. However, it includes extra elements such as arrows and squares around the object. Is there a way to disable these additional elements and only display the arrows? https://i.sstatic.net/Lk ...

Creating a dynamic map in AngularJS by parsing and utilizing data from a JSON file

Looking to create a map from JSON data returned by a RESTFUL WEB Service using AngularJS. Here is an example of the JSON format: myJSON = [{ id: 8, color: "red", value: "#f00" }, { id: 37, color: "green", value: "#0f0" }, { id ...

Unable to load the requested resource: net::ERR_FAILED

I am facing an issue while trying to write React code. When using Chrome, I encountered the following warning: Access to XMLHttpRequest at 'file:///D:/programe/code/Vscode/ReactDemo/HelloWorld/test.js' from origin 'null' has been block ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Is there a method or API available for interacting with an <object> that is currently displaying a video?

Yay, I figured it out! I've been using video.js to play videos on a website that needs to work offline too. Unfortunately, using flash is not an option due to compatibility issues. So, I decided to write my own fallback solution. For Internet Explor ...

Using Webpack to transfer a function to the front-end

I am currently delving into the world of webpack and attempting to set up a basic integration. Within my file script.js, I have included some essential functions: scripts.js export foo = () => { console.log('foo') } export bar = () => ...

Adjust the stacking order of bars in a vertical chart and exclude negative values with Vega-Lite

I am utilizing this chart as a guide for my current project Explore Vega Editor here https://i.sstatic.net/VGOee.png Is there a way to rearrange the order of the 'Measure' while keeping 'Measure 1' at the top, disregarding its negati ...

Ordering ng-repeat in AngularJS using a separate arrayDiscover how to easily order your

Imagine I have an array containing keys in a specific order orderedItems=["apple","banana","orange]; and there is a JSON object that I want to display using ng-repeat but following the sequence specified in the array: {"fruits": { "apple":{ ...

Utilizing parameters for data filtering in VueX getters

I'm really stuck on this issue. I've been trying to retrieve a blog post object using a getter based on its "slug". Despite all my attempts, every time I try to use the getter, I keep getting an error saying "state.posts.filter" is not a function ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...