我有一个组件 HomeComponent 和两个服务:AnimalService 和 DogService
DogService 像这样扩展 AnimalService :
@Injectable({providedIn: 'root'})
export class AnimalService {
constructor() {}
move(): any {
console.log('move animal');
}
}
@Injectable({providedIn: 'root'})
export class DogService extends AnimalService {
constructor() {
super();
}
scream(): any {
console.log('il crie');
}
}
然后我想通过在我的组件中调用 scream 函数来使用它:
@Component({
selector: 'jhi-home',
templateUrl: './home.component.html',
styleUrls: ['home.scss']
})
export class HomeComponent implements OnInit {
constructor(private dogService: DogService) {}
ngOnInit() {
this.dogService.scream(); // the error here : scream is not a function
}
}
但是我有以下错误:
this.dogService.scream is not a function
也许 Angular 微妙之处,因为 Injectable 或类似的东西,我知道 DogService 的构造函数没有被调用,因为我的网络浏览器理解它是一个 AnimalService。如果我执行 dogService = New DogService
而不是在构造函数中声明它,情况就不是这样了。但我不明白为什么。
有什么想法吗?
最佳答案
问题出在您的父类(super class)中的注解。不要注释 AnimalService。它必须是一个抽象的简单类。
export abstract class AnimalService {
constructor() {}
move(): any {
console.log('move animal');
}
}
@Injectable({providedIn: 'root'})
export class DogService extends AnimalService {
constructor() {
super();
}
scream(): any {
console.log('il crie');
}
}
关于javascript - Angular 允许在构造函数中继承服务声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51642613/