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

2

10

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();
  }
}
Gerry answered 12/9, 2016 at 14:22 Comment(0)
Q
12

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.

Querulous answered 12/9, 2016 at 14:35 Comment(0)
S
-1

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
  }
}
Suberin answered 12/9, 2016 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.