Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 DI with ES2016 decorators?

This is the closest I've gotten on github

My service is

@Injectable() export class TodoService {}

But I'm unsure how to inject it into my component using ES2016 decorators. Is it even possible, or are the decorators Typescript-specific? I know in TS there's a emitDecoratorMetadata option.

like image 364
iksose Avatar asked Oct 28 '15 20:10

iksose


1 Answers

  1. Use providers or viewProviders to "provide" service to the component:

  2. Inject service into component constructor specifying parameters types:

@Component({
  // ...
  providers: [TodoService]
})
class TodoComponent() {

  constructor(todoService: TodoService) {
    this.todoService = todoService;
  }
}

or using Inject parameter decorator.

@Component({
  // ...
  providers: [TodoService]
})
class TodoComponent() {

  constructor(@Inject(TodoService) todoService) {
    this.todoService = todoService;
  }
} 

Parameter decorators are not part of the ES2016 (you can consider it as TypeScript specific). But they can be added to the standard later).

If you really want to use ES6/ES7, use static getter for parameters:

@Component({
  // ...
  providers: [TodoService]
})
class TodoComponent() {

  static get parameters() {
    return [[TodoService]]; // you can also return just [TodoService]
  }

  constructor(todoService) {
    this.todoService = todoService;
  }
} 

Also, I recommend you to read this article to better understand angular2 Dependency Injection.

like image 142
alexpods Avatar answered Oct 18 '22 04:10

alexpods