Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Class extends class with injections

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);
    }
}
like image 220
Sampgun Avatar asked Mar 16 '18 10:03

Sampgun


1 Answers

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);
    }
}
like image 123
Titian Cernicova-Dragomir Avatar answered Sep 21 '22 13:09

Titian Cernicova-Dragomir