I am currently digging into DI in Angular 2. I\'m implementing a REST-Client using a generic subtypes for concrete Datatypes like this:
class RESTClient
This should provide a solution for this issue but also help in any case where one needs to inject a service without supplying it as a constructor parameter.
I saw this answer in another post: Storing injector instance for use in components
You can configure the Angular Injector in your AppModule class, and then use it in any other class (you can access AppModule's members from any class).
In AppModule add:
export class AppModule {
/**
* Allows for retrieving singletons using `AppModule.injector.get(MyService)`
* This is good to prevent injecting the service as constructor parameter.
*/
static injector: Injector;
constructor(injector: Injector) {
AppModule.injector = injector;
}
}
Then in your other class you can do the following (for this question replace MyService with Http):
@Injectable()
export class MyClass{
private myService;
constructor(){
this.myService = AppModule.injector.get(MyService);
}
}
This would be equivalent to using:
constructor(private myService: MyService){}