我想知道如何在抽象类中注入具有多个依赖项的服务,该类将被多个类扩展。
然后以一种更有效的方式将其传递给所有构造函数!
我尝试创建静态的,但是如果该服务从未被另一个实例化,则单例实例变量将永远不会分配
这样的事情:(仅是示例)
@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());
在这种情况下,AnimalService
将使用HttpClient
和UserService
。
UserService
将使用更多服务。
那么我怎么能得到一个像这样的const doggo = new Dog();
的类实例化,它会创建/使用/注入AnimalService而不在所有类中传递它?
答案 0 :(得分:0)
我终于找到了解决方法。
以下是我的示例:
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());
对于我来说,它可以工作,希望对您有帮助!