Angular2 DI with ES2016 decorators?

This is the closest I got on github

My service

@Injectable() export class TodoService {}

But I'm not sure how to embed it in my component using ES2016 decorators. Is this possible, or are Typescript-specific decorators? I know that TS has the emitDecoratorMetadata option.

+5
source share
1 answer
  • Use providers or viewProviders to provide services to the component:

  • Enter the service in the component designer by specifying the types of parameters:

 @Component({ // ... providers: [TodoService] }) class TodoComponent() { constructor(todoService: TodoService) { this.todoService = todoService; } } 

or using the Inject parameter Inject .

 @Component({ // ... providers: [TodoService] }) class TodoComponent() { constructor(@Inject(TodoService) todoService) { this.todoService = todoService; } } 

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

If you really want to use ES6 / ES7, use a 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; } } 

In addition, I recommend that you read this article to better understand angular2 Injection Dependency.

+5
source

Source: https://habr.com/ru/post/1234733/


All Articles