Emmanuel Sayson
Emmanuel Sayson

Reputation: 399

Angular use multiple instances of service of parent component to child

I've seen this thread: Using multiple instances of the same service. Is it possible to use same multiple instance of a service from parent to children?

For example, I have an ElementService in ParentComponent and have 2 instances of that service

{ provide: 'instance1', useClass: ElementService},
{ provide: 'instance2', useClass: ElementService},

How should I use instance1 in Child1Component and instance2 in Child2Component?

Upvotes: 3

Views: 2803

Answers (2)

Gérôme Grignon
Gérôme Grignon

Reputation: 4228

You can inject a named provider in the constructor of each child component (and in the parent constructor as well) :

Child1Component

constructor(@Inject('instance1') private service: ElementService) { }

Child2Component

constructor(@Inject('instance2') private service: ElementService) { }

Here is a working example with a counter : https://stackblitz.com/edit/angular-ivy-usorby?file=src%2Fapp%2Fchild1%2Fchild1.component.ts

Upvotes: 1

James
James

Reputation: 2895

When you specify providers in a component's decorator, the providers that are injected become specific to that component see Angular - Providing dependencies

This is also helpful info about dependency injection

So just specify the service in both of the component's providers array and you should have unique instances of the service in both components.

@Component({
    selector: 'app-page',
    templateUrl: './page.component.html',
    styleUrls: ['./page.component.scss'],
    providers: [
        ElementService
    ]
})
export class PageComponent implements OnInit {...

Upvotes: 1

Related Questions