【问题标题】:Angular 2 No provider errorAngular 2没有提供者错误
【发布时间】:2015-07-26 02:41:39
【问题描述】:

我正在创建简单的入门应用程序来使用 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);

有什么问题?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢。我正在做同样的事情。但是,我的应用程序在“injectables:”行崩溃了。因为 TodoService 没有加载,它稍后加载。如果我在同一个文件中声明它很好,但如果它在一个单独的文件中它会稍后出现。我怎样才能避免这种情况?
      • 你可以在构造函数中使用@InjectPromise;见 angular2.src.di.annotations_impl
      • 检查这个答案以获得更新的角度stackoverflow.com/questions/30580083/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-21
      相关资源
      最近更新 更多