10

angular 2で遊ぶためのシンプルなスターターアプリを作成しています.todoサービスを作成してコンポーネントに注入しようとしていますが、次のエラーが発生します:

TodoService のプロバイダーがありません! (TodoList -> TodoService)

TodoService.ts

export class TodoService {
 todos: Array<Object>
 constructor() {
   this.todos = [];
 }
}

app.ts

/// <reference path="typings/angular2/angular2.d.ts" />

import {Component, View, bootstrap, For, If} from 'angular2/angular2';
import {TodoService} from './TodoService'

@Component({
  selector: 'my-app'
})

@View({
  templateUrl: 'app.html',
  directives: [For, If],
  injectables: [TodoService]
})

class TodoList {
 todos: Array<Object>
  constructor(t: TodoService) {
    this.todos = t.todos
  }

  addTodo(todo) {
    this.todos.push({
      done:false,
      todo: todo.value
    });
  }
}

bootstrap(TodoList);

何が問題ですか?

4

2 に答える 2

9

注射剤は、上では@Componentなく上で指定されています@View

あなたが持っている:

@Component({
  selector: 'my-app'
})

@View({
  templateUrl: 'app.html',
  directives: [For, If],
  injectables: [TodoService]  // moving this line
})

次のように変更します。

@Component({
  selector: 'my-app',
  injectables: [TodoService]  // to here
})

@View({
  templateUrl: 'app.html',
  directives: [For, If]
})

これにより、DI がそれを取得してコンポーネントに挿入できるようになります。

于 2015-05-15T10:50:55.013 に答える