Chris Fulstow
Chris Fulstow

Reputation: 41882

Angular 2 dependency injection for decorators

Is there any way to inject a service dependency into a @Component decoration, something like this?

@Component({
    selector: injectedService.getPrefix() + 'my-component'
})
export class MyComponent { }

Or, if not, might it be possible to subsclass @Component and inject a dependency into the subclass to achieve a similar result?

Upvotes: 1

Views: 2083

Answers (1)

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

Reputation: 657248

update >= RC.5

@NgModule({
  ...
})
export class AppModule {
  ngDoBootstrap(moduleRef) {
    appInjector(moduleRef.injector);
  }
}

appInjector implementation see below

original <= RC.5

This is not directly supported by Angular2. You can store the injector outside of your Angular app and then reference it from there like demonstrated as a workaround for the @CanActivate() decorator in https://github.com/angular/angular/issues/4112#issuecomment-153811572. (Plunker example)

In main.ts the injector is assigned to appInjector

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

app-injector.ts

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

    return appInjectorRef;
};

then you can get a reference to the injector like

appInjector()...

This won't work if the component is created before bootstrap() is completed.

Upvotes: 2

Related Questions