Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  }
}
like image 741
karina Avatar asked Sep 12 '16 14:09

karina


People also ask

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

What is hierarchical dependency injection?

With hierarchical dependency injection, you can isolate sections of the application and give them their own private dependencies not shared with the rest of the application, or have parent components share certain dependencies with its child components only but not with the rest of the component tree, and so on.

What is difference between @inject and @injectable?

We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.

How many ways we can do dependency injection in Angular?

There are three types of Dependency Injections in Angular, they are as follows: Constructor injection: Here, it provides the dependencies through a class constructor. Setter injection: The client uses a setter method into which the injector injects the dependency.


1 Answers

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.

like image 172
rinukkusu Avatar answered Oct 22 '22 23:10

rinukkusu