Javascript 在构造函数中允许继承服务声明
我有一个组件HomeComponent,我有两个服务:AnimalService和DogService DogService扩展了AnimalService,如下所示:Javascript 在构造函数中允许继承服务声明,javascript,angular,typescript,inheritance,angular-services,Javascript,Angular,Typescript,Inheritance,Angular Services,我有一个组件HomeComponent,我有两个服务:AnimalService和DogService DogService扩展了AnimalService,如下所示: @Injectable({providedIn: 'root'}) export class AnimalService { constructor() {} move(): any { console.log('move animal'); } } @Injectable({provi
@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');
}
}
然后我想通过在我的组件中调用尖叫函数来使用它:
@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
也许有一个微妙的角度,因为注射或类似的东西,我知道,构造器的DogService没有被称为,我的网络浏览器理解,这是一个动物服务。如果我做一个dogService=newdogservice
而不是在构造函数中声明它,情况就不是这样了。但我不明白为什么
有什么想法吗 问题在于超类中的注释。不要给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');
}
}
您是否尝试过在
模块
中注册您的服务,而不是在标志中注册提供的服务?我认为OP的目的是能够自己使用超类。如果未对其进行注释,则无法将其用作服务。如果这不可能,他/她可能需要重新考虑设计。我同意。我想说明的是,只有当只有一个类
获得可注入注释时,服务之间的继承才会起作用,而这必须是继承类。在这种情况下,将AnimalService
设为抽象类(不带@Injectable),并创建AnimalService
(使用@Injectable)这样,DogService
仍然可以扩展抽象,并且可以创建一个单独的可注入实例created@Lynx谢谢你的回答。是的,我想继续使用AnimalService。所以最后我做了以下工作:我在一个抽象类中复制了AnimalService
,并扩展了DogService
。这样我就可以继续使用AnimalService,如果我想使用DogService的所有功能(都在抽象类和DogService本身中实现)。请毫不犹豫地告诉我这是否是一个好的实践!很高兴听到它对您有效。:-)是的,使用AnimalService和DogService使用的抽象类是一种很好的方法。做得很好。