3

I tried to inject a service (TodoStore) into my component (TodoList) but failed with decorators. The only way it works is with constructor parameter decorators

constructor(@Inject(TodoStore) store)

which is not valid ES7 as i know. I tried to put the inject before the class or before constructor function, neither way worked with Webpack. My current most standard compliant solution is

static get parameters() {
  return [[TodoStore]];
}

My question is there a way with decorators in valid ES6/ES7 to inject dependencies?

VuesomeDev
  • 4,095
  • 2
  • 34
  • 44

2 Answers2

0

In fact, you don't need to use the @Inject annotation. Your service needs to have a @Injectable annotation.

import {Injectable} from 'angular2/core';

@Injectable()
export class TodoStore {
  (...)
}

To be able to inject it into your component simply add it then in the parameters of its constructor and into its providers list:

import {TodoStore} from './todoStore';

@Component({
  selector: 'todo-list',
  providers: [ TodoStore ],
  template: `
    (...)
  `
})
export class TodoListComponent {
  constructor(service:TodoStore) {
    this.service = service;
  }
  (...)
}

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0

Try this:

import {Component, Inject} from 'angular2/core';
import {TodoStore} from './todoStore';

@Component(...)
export class TodoListComponent {
  constructor(service) {
    this.service = service;
  }
  ...
}

// Workaround for parameter annotations
TodoListComponent.parameters = [new Inject(TodoStore)];
Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
  • Technically it is the same as the static getter, just outside the declaration. – VuesomeDev Mar 05 '16 at 17:40
  • This is mostly accurate, only difference here is that you don't need to use Inject at all. If you just put the World class into the parameters, then the injector will take care of instantiating it for you. – monokrome Jun 16 '16 at 05:04