Angular 5 Class extends class with injections
Asked Answered
T

1

5

I created such a class

@Injectable FooService {

    constructor(private _bar:BarService){

    }
}

And extended it like this

@Injectable ExtFooService extends FooService {

    constructor(private _bar:BarService){
        super(_bar);
    }
}

In this way I get the following error:

Error:(12, 14) TS2415:Class 'ExtFooService' incorrectly extends base class 'FooService'. Types have separate declarations of a private property '_bar'.

Why is that so?

I tried removing the injections from the ExtFooService, but I get this at the super() line:

Error:(21, 9) TS2554:Expected 2 arguments, but got 0.

Is it really necessary that I do this?

@Injectable ExtFooService extends FooService {

    constructor(private _extBar:BarService){
        super(_extBar);
    }
}
Tubb answered 16/3, 2018 at 10:3 Comment(0)
C
9

You should remove the private from the argument _bar in the derived class. The private is short hand for declaring a field with the same name as the constructor argument and initializing it with the value of the argument. Since the base class already declared the field, there is no need to redeclare it in the derived class:

@Injectable ExtFooService extends FooService {

    constructor(_bar:BarService){
        super(_bar);
    }
}
Chorister answered 16/3, 2018 at 10:5 Comment(4)
And this doesn't make _bar public?Tubb
@TonySamperi If you want the argument to be a public field you would have to explicitly add public. If you don't specify any modifier it is just a constructor argument not a class memeberChorister
Cool. Thank youTubb
Wow thanks, I've been searching for about an hour just to find that private was blocking the whole thing. In my case though, it was in the class that extends the base class, where the key word private needed to be removed.Perichondrium

© 2022 - 2024 — McMap. All rights reserved.