Crocsx
Crocsx

Reputation: 7589

Create a double instance of a service in my angular app

I have a Generic service. I would like to create two instance of this service with different type =>

constructor(
  private mapSynchService: 
SynchronizatorService<SynchMapElement, SynchMapElementSubject>,
  private waypointSynchService: 
SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>) { }

The problem, I thought this would create two different service cause the definition is different, but it is not doing so. But I don't quite understand how I can make those service available in all my module, and get the correct one for the component that need service 1, and same for those who need service 2.

I have seen some post about injection token, but my implementation failed. I tried something like this in the module

providers: 
  [{provide: 
    new InjectionToken<SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>>()}]

But got a lot of error

Upvotes: 0

Views: 242

Answers (1)

ashish.gd
ashish.gd

Reputation: 1768

You will need two separate injection tokens for providing separate instances.

Each token works like a unique name to value/class/factory mapping for the Angular DI container. Also make sure the service is marked @Injectable for Angular to recognise it.

Example:


// Export unique Injection Token

export const SYNCH_MAP = new InjectionToken<SynchronizatorService<SynchMapElement, SynchMapElementSubject>>('Token for SynchMap');
export const SYNCH_WAYPOINT = new InjectionToken<SynchronizatorService<SynchWaypointElement, SynchWaypointElementSubject>>('Token for SynchWaypoint');

// Using at a module level

@NgModule({
    ...
    providers: [
        { provide: SYNCH_MAP, useClass: SynchronizatorService<SynchMapElement, SynchMapElementSubject> }
        { provide: SYNCH_WAYPOINT, useClass: SynchronizatorService<SynchMapElement, SynchMapElementSubject> }
    ]
})


// Injecting in a component 

constructor(
    @Inject(SYNCH_MAP) private instance1: SynchronizatorService<SynchMapElement, SynchMapElementSubject>,
    @Inject(SYNCH_WAYPOINT) private instance2: SynchronizatorService<SynchMapElement, SynchMapElementSubject>,
)

IMO, it would be better to use a useFactory provider for having more control on initialising the service instances. As I assume your service definition is using a template <T>. Please have a look at https://angular.io/guide/dependency-injection-providers#predefined-tokens-and-multiple-providers

Upvotes: 1

Related Questions