Javascript Angular 2 没有提供者错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30238057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:50:47  来源:igfitidea点击:

Angular 2 No provider error

javascriptangular

提问by

I am creating simple starter app to play with angular 2 and i am trying to make a todo service and inject him to my component and i get this error:

我正在创建简单的入门应用程序来使用 angular 2,我正在尝试制作一个待办事项服务并将他注入我的组件中,但出现此错误:

No provider for TodoService! (TodoList -> TodoService)

TodoService 没有提供者!(TodoList -> TodoService)

TodoService.ts

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

What is the problem?

问题是什么?

采纳答案by Brocco

The injectables are specified on the @Componentnot on the @View

注射剂被指定在@Component@View

You have:

你有:

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

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

Change it to:

将其更改为:

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

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

This will allow DI to pick it up and inject it into your component.

这将允许 DI 拾取它并将其注入到您的组件中。

回答by sachinkasana

In the latest Angular version, you have to use providers instead of injectables, for example:

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

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