Angular 2 没有提供商错误

Angular 2 No provider error

我正在创建简单的入门应用程序来与 angular 2 一起玩,我正在尝试制作待办事项服务并将其注入我的组件,但我收到此错误:

没有 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);

问题是什么?

注射剂在 @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 获取它并将其注入到您的组件中。

在最新的 Angular 版本中,您必须使用提供程序而不是注射器,例如:

@Component({
    selector: 'my-app',
    providers: [TodoService]
})