tom10271
tom10271

Reputation: 4649

@Inject outside Angular2 application

Is it possible to retrieve any @Injectable like:

var config = @Inject(Config);

Thanks

Upvotes: 2

Views: 677

Answers (2)

Timothy Zorn
Timothy Zorn

Reputation: 3229

I found it easier to declare injector as a global variable so I could use it a bit easier.

In the file where you bootstrap angular:

declare global {
    var injector: Injector;
}

bootstrap(/* your bootstrap stuff */).then((appRef) => {
    injector = appRef.injector;
});

The above will give you access to an injector variable anywhere else in your code.

In the file where you need an instance of Config:

import { Config } from './path/to/config.service';

class TestClass {
    private config: Config;

    constructor() {
        this.config = injector.get(Config);
    }
}

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657416

If you want to get new instances from dependency injection, you need a reference to the Injector then you can acquire new instances with

injector.get(Config);

How you can get a reference to Injector depends on where your code is.
In an Angular component or service, just inject it

constructor(private injector:Injector) {}

You can also just create your own injector like

var injector = Injector.resolveAndCreate([Car, Engine]);

where Car and Engine are the providers the injector can create instances for.

To get the injector of your Angular application to be used outside your Angular application you can use

Example from https://github.com/angular/angular/issues/4112#issuecomment-153811572

let appInjectorRef: Injector;
export const appInjector = (injector?: Injector):Injector => {
    if (injector) {
      appInjectorRef = injector;
    }

    return appInjectorRef;
};

bootstrap(App, [
  Auth,
  HTTP_PROVIDERS,
  ROUTER_PROVIDERS,
  Car,
  Engine
]).then((appRef: ComponentRef) => {
  // store a reference to the application injector
  appInjector(appRef.injector);
});

let injector: Injector = appInjector();
injector.get(Car);

Upvotes: 2

Related Questions