Search code examples
angulartypescriptdependency-injectioninjectinjectable

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


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();
  }
}


Solution

  • 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.