代码之家  ›  专栏  ›  技术社区  ›  Couim

构造函数中的角度允许继承服务声明

  •  2
  • Couim  · 技术社区  · 6 年前

    我有一个组件homecomponent,我有两个服务:animalservice和dogservice

    Dogservice像这样扩展动画服务:

    @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的构造函数不是被调用的,因为我的webbrowser承诺它是一个动画服务。如果我做一个 dogService = New DogService 而不是在构造函数中声明它。但我不明白为什么。

    有什么想法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Lynx 242    6 年前

    问题是超类中的注释。不要注释动画服务。它必须是一个抽象的简单类。

    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');
        }
    }