Angular 2: Inject service into class

I’ve managed to resolve my problem.

Angular 2 – 4 provides reflective injector that allows to inject dependencies outside of constructor parameters.

All I had to do was to import Reflective injector from @angular/core.

import {ReflectiveInjector} from '@angular/core';

And then:

let injector = ReflectiveInjector.resolveAndCreate([DrawingService]);
this.drawingApi = injector.get(DrawingService);

The class doesn’t even have to be decorated with the @Injectable decorator.
The only problem is that I have to provide all dependencies for DrawingService and all the nested dependencies, so that is hard to maintain.

EDIT:

Angular 5

import { Injector } from "@angular/core";

const injector = Injector.create([
    { provide: DrawingService }
]);
this.drawingApi = injector.get(DrawingService);

Angular 6

import { Injector } from "@angular/core";

const injector = Injector.create({ 
  providers: [ 
    { provide: DrawingService },
  ]
});
this.drawingApi = injector.get(DrawingService);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)