问题
Is it possible to do something like this? (cause I tried, and haven't succeed):
@Injectable()
class A {
constructor(private http: Http){ // <-- Injection in root class
}
foo(){
this.http.get()...
};
}
@Injectable()
class B extends A{
bar() {
this.foo();
}
}
回答1:
Kind of - you have to make a super
call to the constructor of your base class. Just pass down the needed dependencies:
@Injectable()
class A {
constructor(private http: Http){ // <-- Injection in root class
}
foo(){
this.http.get()...
};
}
@Injectable()
class B extends A{
constructor(http: Http) {
super(http);
}
bar() {
this.foo();
}
}
See this discussion, why there is no way around it.
回答2:
This will solve your problem for sure.
@Injectable()
class A {
constructor(private http: Http){ // <-- Injection in root class
}
foo(http:Http){ //<------receive parameter as Http type
http.get()... //<------this will work for sure.
};
}
import {Http} from '@angular/http';
@Injectable()
class B extends A{
constructor(private http:Http){}
bar() {
this.foo(this.http); //<----- passing this.http as a parameter
}
}
来源:https://stackoverflow.com/questions/39452578/how-should-i-extend-injectable-from-another-injectable-with-many-injections-in-a