How should I extend Injectable from another Injectable with many Injections in angular2?

爱⌒轻易说出口 提交于 2020-06-14 04:09:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!