0

I have a service ServiceA which has its own states (instance variables, etc) and in my module I have multiple instances of service ServiceA.

@Injectable()
export class ServiceA { 
  // It defines instance variables.
}

Since I need to have multiple instances of ServiceA, I am not able to make it a module-level component.

In ComponentB instantiate a ServiceA instance and can potentially change its state:

@Component({
  providers = [ServiceA],
})
export class ComponentB {
  // changes the state of ServiceA.
}

Also in the HTML template of ComponentB I have a route to ComponentC, which needs to access the same ServiceA instance:

<a routerLink="/path_to_component_c"></a>

And here is the definition of ComponentC:

@Component({
  providers = [],
})
export class ComponentC {
  // accesses ServiceA.
}

If ServiceA was a module-level component, there won't be issues sharing it across ComponentB and ComponentC, since they are both in the same module. However, since ServiceA is injected into ComponentB directly, I am not able to do so anymore. Note that every time only one ComponentC will be created and ComponentC is created after ComponentB.

Is there a way to share data between ComponentB and ComponentC? Thanks!

Lee7355512727
  • 69
  • 2
  • 10

1 Answers1

0

It sounds like you want to use ServiceA as a factory rather than a singleton. This can be accomplished with a Factory Provider.

See also this answer.

Is there a way to share data between ComponentB and ComponentC? Thanks!

There are a few ways. A service is one (yes, you can have a service for instances of your factory!). If ComponentC is a child of ComponentB, you could use an input.

Jefftopia
  • 2,105
  • 1
  • 26
  • 45