Freddy Bonda
Freddy Bonda

Reputation: 1259

Angular not-global singleton service

I know how to create a singleton service for my entire program to use (by declaring it in the app.module). But I would like to create a service that is only a singleton to all the components below it. So for example:

In this hierarchy, I would like Service to be a singleton that can only be used by Children 1.x, NOT by Main2 or Child2. Here is my service:

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService {
   ...
}

But MUST I import this service in app.module? If I import it in app.module then it is global, I don't want it to be global.

Upvotes: 0

Views: 89

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39482

That's what Angular's Hierarchical Dependency is all about.

A Component also has a providers array. You can add your service to that array. And then this Component and any of its child Component will share the same singleton.

So your Main1 will have a RootComponent in it. In it's @Component metadata, just add a providers array and specify the token for your Service there.

This is what it would look like in code:

@Component({
  ...,
  providers: [ SharedService ]
})
export class Main1Component { ... }

So now that you've done that, the SharedService will only be accessible by Main1, Child1.1, Child1.1.1, and Child1.2


Consider the example that I have in this Working Sample StackBlitz.

Here we have two Component Hierarchies(Main 1 and Main 2). Both Main1 and Main2 have added the SharedService to the providers array of their @Component Decorator Metadata.

Due to this, Main 1 and its Children will have it's own instance of the SharedService. And Main 2 and its Children will have its own instance of the SharedService. These two instances would NOT BE SAME.

That's the reason why only the Main1 and its Children's message change when I click the first Button that says: Change the SharedData - This will only change the SharedData for Main 1 and it's Children

And same would be the case with Button 2 as it will only update the Contents of Main 2 and it's Children.

Hope this explanation helps. Do have a look at the Sample StackBlitz and it will be more clear.

Upvotes: 2

Related Questions