The child module's services are accessible and utilized by the components of the parent module

I have an Angular application structured as follows:

Data Module
     --> Data Component
     --> Data Service
List Module
  --> imports Data Module
   --> List Component
          --> which calls Data Component
   --> Parent List Component
          --> which in turn calls List Component
  1. The Data service functions correctly when using the List component.
  2. However, when using the Parent List component, it renders the List component which then renders the Data component. The issue is that the Data service is shared and behaves in the same way as step 1.

It seems like I should have created a separate instance of the Data service.

If you have any suggestions or insights on what I might be missing, they would be greatly appreciated.

Thank you.

Answer â„–1

The extent of your service's reach is determined by how and where you choose to offer it.

If you specify your service as providedIn: 'root', only a single global instance will be generated and utilized across all modules or components where the service is supplied.

@Injectable({
  providedIn: 'root'
})
class DataService {
    // A unique DataService accessible throughout various modules
}

Alternatively, you can limit a service's scope by adjusting the value of providedIn. For more information, visit this documentation link.

You may also opt to exclude the providedIn parameter altogether, enabling you to provide the service at the component level. Consider the following example:

// Service declared as @Injectable without providedIn
@Injectable()
class DataService {
    // The service remains inactive until instantiated within a specific component
}

In this scenario, the service will be created only when included in a component's providers array, like so:

@Component({
  selector: 'app-list',
  template: ``,
  styleUrl: ``,
  providers: [
    DataService
  ]
})
export class ListComponent {
  constructor(private dataService: DataService) {}
}

@Component({
  selector: 'app-parent-list',
  template: `<app-list></app-list>`,
  styleUrl: ``,
})
export class ParentListComponent {
  constructor(private dataService: DataService) {}
}

This setup ensures that DataService is instantiated solely upon creation of a ListComponent, with the instance being discarded once the associated ListComponent is destroyed.

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

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Add a Filter to the Observer (__ob__) in Typescript

I am trying to implement a filter using this.Grid.option("dataSource").filter(x => x.Placeholder != null) however, it doesn't seem to be working when I run console.log(this.Grid.option("dataSource")); I receive (72) [{…}, {…}, {…}, {†...

After importing this variable into index.ts, how is it possible for it to possess a function named `listen`?

Running a Github repository that I stumbled upon. Regarding the line import server from './server' - how does this API recognize that the server object has a method called listen? When examining the server.ts file in the same directory, there is ...

Having trouble retrieving the JSON data from the getNutrition() service method using a post request to the Nutritionix API. Just started exploring APIs and using Angular

When attempting to contact the service, this.food is recognized as a string import { Component, OnInit } from '@angular/core'; import { ClientService } from '../../services/client.service'; import { Client } from '../../models/Cli ...

Angular Validators are behaving inconsistently, as they only work intermittently before stopping altogether once the application is

Why does my code sometimes behave differently after running for a while and then return to normal after restarting the Angular server without making any changes?The pop-up that says "please fill out this field" disappears when it shouldn't This is th ...

When using TypeScript with Jest or Mocha, an issue arises where the testing frameworks are unable to read JavaScript dependencies properly, resulting in an error message saying "unexpected token

Currently, I am conducting testing on a TypeScript file using Mocha. Within the file, there is a dependency that I access via the import statement, and the function I need to test resides within the same file as shown below: import { Foo } from 'foo- ...

What is the correct way to invoke a function that accepts a combination of specific string values when all I have is a regular string?

Within the TypeScript function declaration provided below, the parameter type alignment consists of unioned literals. function printText(s: string, alignment: "left" | "right" | "center") { // ... } As per the documentation ...

"Navigating through events with confidence: the power of event

Imagine I am developing an event manager for a chat application. Having had success with event maps in the past, I have decided to use them again. This is the structure of the event map: interface ChatEventMap { incomingMessage: string; newUser: { ...

What could be causing my Angular 7 project to have an overwhelming 40000 packages? Any tips on how to efficiently eliminate unnecessary dependencies?

Upon running npm audit in my terminal, the output displays: [...] found 0 vulnerabilities in 40256 scanned packages I'm puzzled by the fact that my project contains over 40,000 packages. This number seems excessive as I haven't intentionally ad ...

Updating the value of a form control in Angular2

I am facing an issue when trying to create dynamic Angular 2 forms with controls and select boxes, like in this example on Plunker: <select class="form-control" ngControl="power"> <option *ngFor="#p of powers" [value]="p">{{p}}</o ...

Ways to avoid redundancy in Gitlab CI/CD when utilizing multiple stages

Currently, my workflow involves utilizing gitlab CI/CD for deploying my angular app on firebase. This process consists of 2 stages: build and deploy. image: node:11.2.0 stages: - build - deploy cache: paths: - node_modules/ build: stage: bu ...

Tips for ensuring the correct typing of a "handler" search for a "dispatcher" style function

Imagine having a structure like this: type TInfoGeneric<TType extends string, TValue> = { valueType: TType, value: TValue, // Correspond to valueType } To prevent redundancy, a type map is created to list the potential valueType and associate i ...

Guide to importing a Swagger model barrel file into a Typescript file (Angular)

Our team is currently using Swagger to automatically generate our API models and we are looking for a more convenient way to import them into our project. Currently, we are importing them like this: tsconfig.ts "paths": { "apimodel/*": ["frontend/swagg ...

The TS type guard fails to identify a non-empty property in a class object

Encountering an issue with TypeScript that involves a class property typed as AmplitudeFeatureFlags | {} = {}; initialized as an empty object. Attempting to retrieve a value from this class property using a method that takes in a property name argument of ...

How to extract multiple variables from a URL using Angular 2

I need to parse multiple parameters from a URL. Let's consider the following URL structure: www.example.com/parent-component/2/list/child-component/5/list The parameters I want to extract are 2 and 5 This is the link on the parent component: [rout ...

Can React Hooks API be used in TypeScript without using JSX?

After attempting to convert the JSX version of the React Hooks API demo into one without JSX, following the guidelines provided in react-without-jsx documentation, I ended up with the code below: import React, { useState } from 'react'; import R ...

Transitioning from AngularJS to Angular: Updating the factory prototype

I've been in the process of migrating from AngularJS to Angular and have made a lot of progress. However, I am currently facing challenges with factories and prototypes. In this context, the Card object represents a playing card. function Car ...

Currently, I am collaborating on an e-commerce endeavor utilizing TypeScript and sanity.io, encountering an issue along the way

Encountering an Uncaught TypeError message: Cannot read properties of undefined (reading '_ref'). While attempting to utilize code for displaying API content on a webpage, what might be causing this issue and how can it be resolved to successful ...

Typescript Vue Plugin

I am currently working on developing a Vue logger plugin export default new (class CustomLogger { public install(Vue: any) { Vue.prototype.$log = this; } error(text: string) { console.log(text) } })(); This code is located in main.ts f ...

Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo ...