I am faced with a situation where I have 2 distinct interfaces:
export interface IUserService {
...
}
export interface IUserStorageService {
...
}
In order to consolidate functionalities from both interfaces, I have created a single service that implements them:
@Injectable()
export class UserService implements IUserService, IUserStorageService {
...
}
(Although it may not directly impact my question, I can easily convert these interfaces into abstract classes for smoother integration as tokens without the need for additional injection tokens.)
In Angular, interfaces cannot be used as tokens for providers, so I had to introduce injection tokens:
export let USER_SERVICE: InjectionToken<IUserService> = new InjectionToken<IUserService>("user.service");
export let USER_STORAGE_SERVICE: InjectionToken<IUserStorageService> = new InjectionToken<IUserStorageService>("user-storage.service");
With these injection tokens in place, I proceeded to globally map them to the single service class within my app.module.ts
:
@NgModule({
...
providers: [
{ provide: USER_SERVICE, useClass: UserService },
{ provide: USER_STORAGE_SERVICE, useClass: UserService }
],
...
})
export class AppModule {
...
}
Subsequently, I am now able to inject the service under different interfaces into my components:
// Component A - accesses service's functions through IUserService
constructor(@Inject(USER_SERVICE) private readonly userService: IUserService) {
}
// Component B - accesses service's functions through IUserStorageService
constructor(@Inject(USER_STORAGE_SERVICE) private readonly userStorageService: IUserStorageService) {
}
The challenge arises when Angular creates separate instances of UserService
for each token whereas I require only one shared instance throughout the app.
Is there a way to achieve this desired behavior?