【问题标题】:How should I extend Injectable from another Injectable with many Injections in angular2?我应该如何从另一个 Injectable 扩展 Injectable 并在 angular2 中有许多注入?
【发布时间】:2017-01-20 00:35:56
【问题描述】:
有可能做这样的事情吗? (因为我试过了,但没有成功):
@Injectable()
class A {
constructor(private http: Http){ // <-- Injection in root class
}
foo(){
this.http.get()...
};
}
@Injectable()
class B extends A{
bar() {
this.foo();
}
}
【问题讨论】:
标签:
angular
typescript
dependency-injection
inject
injectable
【解决方案1】:
有点-您必须对基类的构造函数进行super 调用。只需传递所需的依赖项:
@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();
}
}
见this discussion,为什么没有办法绕过它。
【解决方案2】:
这肯定会解决您的问题。
@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
}
}