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.
Use providers or viewProviders to "provide" service to the component:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With