Will Angular inject more than one instance of a generic Service if it is invoked across Component constructors using different Types?
I have a lot of Services that a
This is a simple solution:
// service and models
export class User {
firstName: string
}
export class Admin {
lastName: string
}
@Injectable()
export class GenericService{
item: number = Math.random();
GetAll(): Array {
let output = [];
console.log(this.item); // each instance has own value
return output;
}
}
Then set your service in module through useFactory:
providers: [
{ provide: 'UserService', useFactory: () => (new GenericService()) },
{ provide: 'AdminService', useFactory: () => (new GenericService()) },
],
and inject your service with @Inject decorator:
constructor(
@Inject('UserService') private userService: GenericService,
@Inject('AdminService') private adminService: GenericService
) { }
Keep in mind it is better to use InjectionToken ( OpaqueToken is deprecated) for your provider token.I have used string just for simplicity.