This is a simple solution:
// service and models export class User{ firstName:string } export class Admin{ lastName:string } @Injectable() export class GenericService<T>{ item:number = Math.random(); GetAll():Array<T> { let output = []; console.log(this.item); // each instance has own value return output; } }
Then install your service in the module through useFactory:
providers: [ {provide:'UserService', useFactory:()=>(new GenericService<User>())}, {provide:'AdminService', useFactory:()=>(new GenericService<Admin>())}, ],
and enter your service using the @Inject decorator:
constructor(@Inject('UserService') private userService:GenericService<User>, @Inject('AdminService') private adminService:GenericService<Admin> ) { }
Keep in mind that it is better to use an InjectionToken ( OpaqueToken is deprecated) for your token provider. I used the string just for simplicity.
Himen source share