3

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?

Emmanuel Sayson
  • 279
  • 3
  • 14

2 Answers2

1

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

Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18
  • Hi Gerome, thanks but what I need is that the 2 instances should be declared in parent because parent will also subscribe to the 2 instances of the service. In your example, AppComponent will also listen for the changes in DataService instances of child1 and child2. – Emmanuel Sayson Jul 30 '20 at 09:27
  • inject the providers inside the parent component too. I updated the stackblitz example. – Gérôme Grignon Jul 30 '20 at 09:55
  • hi, are you able to answer this? https://stackoverflow.com/questions/64274610/angular-parent-component-use-different-instance-of-child-component-service –  Oct 09 '20 at 05:57
  • hello, the answer already included in issue(adding the service as a provider directly into the component metadata) should work. – Gérôme Grignon Oct 09 '20 at 10:03
0

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 {...
James
  • 2,516
  • 2
  • 19
  • 31