Reputation: 2432
I will like to know how to inject a service with multiple dependencies inside an abstract class who will be extended by multiple classes.
In a more efficient way then passing it in all constructor!
I try to create static, but if the service is never instantiated by another, the singleton instance variable will never be assigned
Something like this: (Is just an example)
@Injectable({
providedIn: 'root'
})
export class AnimalService {
constructor(private http: HttpClient, private userService: UserService) {}
countTotalInDB(type): number {
return this.http.get(...);
}
getUserAnimals(userId: number) {
return this.userService.getUser(userId).animals;
}
}
abstract class Animal {
constructor() {}
public getTotalInDataBase(type): number {
// How to get a instance of AnimalService ?
return animalService.countTotalInDB(type);
}
}
export class Cat extends Animal {
constructor() {
super();
}
public getTotalInDataBase(): number {
return super.getTotalInDataBase('cat');
}
}
export class Dog extends Animal {
constructor() {
super();
}
public getTotalInDataBase(): number {
return super.getTotalInDataBase('dog');
}
}
const doggo = new Dog();
console.log(doggo.getTotalInDataBase());
In this case, AnimalService
will use HttpClient
and UserService
.
UserService
will use a lot more services.
So how can I get a class instantiation who look like this const doggo = new Dog();
who will create/use/inject the AnimalService without passing it in all classes?
Upvotes: 3
Views: 2145
Reputation: 2432
I finally find how to do this.
Following my example:
import { inject } from '@angular/core'; // Answer
@Injectable({
providedIn: 'root'
})
export class AnimalService {
constructor(private http: HttpClient, private userService: UserService) {}
countTotalInDB(type): number {
return this.http.get(...);
}
getUserAnimals(userId: number) {
return this.userService.getUser(userId).animals;
}
}
abstract class Animal {
protected animalService: AnimalService; // Answer
constructor() {
this.animalService = inject(AnimalService); // Answer
}
public getTotalInDataBase(type): number {
// How to get a instance of AnimalService ?
return this.animalService.countTotalInDB(type);
}
}
export class Cat extends Animal {
constructor() {
super();
}
public getTotalInDataBase(): number {
return super.getTotalInDataBase('cat');
}
}
export class Dog extends Animal {
constructor() {
super();
}
public getTotalInDataBase(): number {
return super.getTotalInDataBase('dog');
}
}
const doggo = new Dog();
console.log(doggo.getTotalInDataBase());
It works in my case, hope it will help you too!
Upvotes: 8