When using Angular, a service can be declared in the viewProviders of the parent component and then accessed in the viewProviders of the child

Imagine a scenario where there is a parent component called AppComponent, a directive named MyDirective, and a service named SimpleService.

In this case, MyDirective is utilized in the template of AppComponent and injects SimpleService using the Host decorator. To avoid using the instance from the parent of AppComponent, a new instance is created within the viewProviders of AppComponent.

However, a situation arises with the introduction of a child component called HelloComponent under AppComponent. Now, HelloComponent also uses MyDirective, but in this case, I want the MyDirective inside HelloComponent to utilize the same instance of SimpleService from AppComponent. How can this be achieved?

I attempted utilizing

{provide: SimpleService, useExisting: SimpleService}
, but it resulted in a cyclic dependency error.

Sample code: https://stackblitz.com/edit/angular-7h352z?file=src%2Fapp%2Fhello.component.ts

Answer №1

To implement this as a singleton service, all you need to do is apply the following decorator to your code:

@Injectable({
  providedIn: 'root',
})

By adding this code snippet, you will ensure that there is only one instance of this service created and shared throughout your application.

Answer №2

Utilize the providers property to make a provider accessible to both its content children and view children.

Give this a shot:

providers: [{provide: NewService, useValue: NewService }]

See Example

Answer №3

Utilize the @SkipSelf() decorator in the constructor

@Component({
  selector: 'hello',
  template: `child <input myDirective >{{value}}`,
  styles: [`h1 { font-family: Lato; }`],
  viewProviders: [SimpleService]

})
export class HelloComponent implements OnInit  {
  constructor(@Host() @Optional() @SkipSelf() private simpleService: SimpleService) {}
  value:any
  ngOnInit()
  {
    this.value=this.simpleService?this.simpleService.message:"No service"
  }
}

Please note that if you need both services, you can inject the own service as follows:

constructor(
     @Host() @Optional() @SkipSelf() private simpleService: SimpleService
     private simpleServiceChild:SimpleService
   ) {}

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 presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

Switching cell icon when clicked - A step-by-step guide

I have a situation in ag-grid where I need to update the icon of a button in a cell when it is clicked to indicate progress and then revert back to its original state upon completion of the action. Below is the code snippet: my-custom.component.ts < ...

Issues with Angular 4 functionality on Tizen Smart TV

After developing a basic Angular4 application, I transformed it into a Tizen web app. Surprisingly, the app functions properly on major browsers like Safari, Chrome, and Firefox, but only displays an empty page with an empty () element. During debugging i ...

Creating interactive features for a TypeScript interface

I was looking to create a dynamic interface with custom properties, like so: data: dataInterface []; this.data = [ { label: { text: 'something', additionalInfo: 'something' } }, { bar: { text: ' ...

The callback function `(err: any, data: any) => void` does not share any properties with the type `RequestInit`

Inspired by the tutorial at , I am working on a time-based visualization. I am currently using version "d3": "^5.4.0". Here is the code snippet: d3.json('http://127.0.0.1:5000', function (err, data) { if (err) throw err; // Cre ...

"Exploring the process of extracting data from a JSON URL using NextJS, TypeScript, and presenting the

After tirelessly searching for a solution, I found myself unable to reach a concrete conclusion. I was able to import { useRouter } from next/router and successfully parse a local JSON file, but my goal is to parse a JSON object from a URL. One example of ...

Error encountered when asynchronously iterating over an object in TypeScript

Could someone please help me understand why I am getting an error with this code? var promise = new Promise((resolve, reject) => { resolve([1, 2, 3, 4, 5]); }); async function doSomethingAsync() { var data = await promise; data.forEach(v = ...

Preserving ES6 syntax while transpiling using Typescript

I have a question regarding keeping ES6 syntax when transpiling to JavaScript. For example, if I write the following code: class Person { public name: string; constructor(name: string) { this.name = name; } } let person = new Person('John D ...

Fetching data from one component to load an Angular component

Essentially, I have a grid within Ionic that dynamically populates its rows using ngFor. Each row contains an ionic button labeled "View details" which, when clicked, should display all the data associated with that specific object. Imagine it as a preview ...

Exploring data retrieval from nested arrays of objects in TypeScript/Angular

I have an API that returns an object array like the example below. How can I access the nested array of objects within the JSON data to find the role with roleid = 2 when EmpId is 102 using TypeScript? 0- { EmpId: 101, EmpName:'abc' Role : ...

What is the best approach for conducting unit tests on model interfaces with TypeScript?

export interface Person { fullName: string; } What is the best way to create unit tests for the above interface and ensure that Karma includes it in the code coverage report? I attempted to assert properties by creating an object, but it seems that K ...

Tips for customizing components in React-Table by overriding default columns

In a nutshell, I was tasked with developing a table component using react-table. By default, the table uses an input component that allows instant typing when double-clicked. Additionally, I wanted one of the columns in editableCell to use a dropdown. I ...

Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using setTimeout( #action#, timeMillis) with #action# as a lambda 2) supplying the lambda with a parameter. The common method of setTimeout( ()=>{ #callback# }, timeMillis) works flawlessly when extracting () ...

The relationship between Vue TypeScript props is influenced by the presence of another prop

Is there a way to define a property in <script setup lang="ts"> that depends on another property? For instance, how can I require a variable only if another variable is present? I attempted using defineProps<Props | PropsA>(), but e ...

Undefined error encountered in the Google Places library

I'm new to working with the Ionic framework and was experimenting with implementing an autocomplete search feature using the Google Maps API. After going through several resources, I included the following code: <script type="text/javascript" src ...

Experimenting with throws using Jest

One of the functions I'm testing is shown below: export const createContext = async (context: any) => { const authContext = await AuthGQL(context) console.log(authContext) if(authContext.isAuth === false) throw 'UNAUTHORIZED' retu ...

Determine user connectivity in Angular 4 using Firebase

My current setup involves using Firebase for authentication with Google. However, I am encountering an issue where upon refreshing the page after being connected, I am unable to retrieve the Session/CurrentUser information. firebase.auth().onAuthStateChan ...

The element access has been upgraded to utilize ng-content

I attempted to create a tabs component that could be used similarly to Angular Material Component. However, the solution I came up with was flawed and buggy. In this attempt, I utilized document.getElementsByTagName('app-tab'). This is the temp ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

How do I retrieve a specific svg element in Angular among multiple elements?

I recently delved into learning Angular for a new project. One of my main objectives was finding a way to dynamically alter the styles of SVG elements. This led me to utilizing ViewChild and ElementRef. Here is an example from the HTML: <svg><g ...