最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 No provider error - Stack Overflow

programmeradmin0浏览0评论

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:

No provider for 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);

What is the problem?

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:

No provider for 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);

What is the problem?

Share Improve this question edited Jul 28, 2017 at 17:01 P.S. 16.4k14 gold badges64 silver badges86 bronze badges asked May 14, 2015 at 12:59 user4207046user4207046
Add a comment  | 

2 Answers 2

Reset to default 9

The injectables are specified on the @Component not on the @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.

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

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

评论列表(0)

  1. 暂无评论