Couim
Couim

Reputation: 747

Angular allow inheritance service declaration in constructor

I've a component HomeComponent and I have two services : AnimalService and DogService

DogService extends AnimalService like that :

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

And then I want to use it by calling scream function inside my component :

    @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
        }
    }

But I have the following error :

this.dogService.scream is not a function

Maybe there is a subtility with angular, becaus of Injectable or something like that, I know that the constructor of DogService is not called, si my webbrowser undertands that it's an AnimalService. it's not the case if I do a dogService = New DogService instead of declaring it inside the constructor. But I don't understand why.

Any ideas ?

Upvotes: 2

Views: 63

Answers (1)

user6749601
user6749601

Reputation:

The problem is the annotation in your SuperClass. Don't annotate AnimalService. It must be an abstract simple class.

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

Upvotes: 1

Related Questions