我有一个组件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
也许由于Injectable或类似的东西存在角度的微妙性,我知道DogService的构造函数没有被调用,因为我的Web浏览器强调它是AnimalService。如果我执行dogService = New DogService
而不是在构造函数中声明它,则不是这种情况。但是我不明白为什么。
有什么想法吗?
答案 0 :(得分:1)
问题是您的SuperClass中的注释。不要注释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');
}
}