How to use Angular2 dependency injection using javascript decorators?

I tried to enter the service (TodoStore) in my component (TodoList), but could not with the decorators. The only way this works is with constructor parameter constructors

constructor(@Inject(TodoStore) store)

which is not valid ES7 as I know. I tried to put the injection in front of the class or before the constructor function, none of the methods worked with Webpack. My present most standard solution is

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

My question is: is there a way with decorators in valid ES6 / ES7 for dependency injection?

+4
source share
2 answers

@Inject. @Injectable.

import {Injectable} from 'angular2/core';

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

, :

import {TodoStore} from './todoStore';

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

, , Thierry

0

:

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)];
0

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


All Articles