Can anyone provide guidance on how to incorporate a service with multiple dependencies into an abstract class that will be inherited by several classes, in a more streamlined manner than passing it through all constructors?
I attempted to utilize static methods, but encountered the issue where the singleton instance variable would not be initialized if the service was never instantiated elsewhere.
Illustrated below is a simplified 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 can we access an instance of AnimalService here?
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 the scenario presented above, AnimalService
relies on HttpClient
and UserService
.
UserService
may further depend on additional services.
So how can I achieve class instantiation similar to const doggo = new Dog();
, which handles the creation/use/injection of AnimalService without explicit declaration in every class?