Angular 2 Provider Error

I am creating a simple beginner application to play with angular 2, and I try to make a todo service and attach it 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?

+8
javascript angular
source share
2 answers

Injections specified in @Component not on @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 insert it into your component.

+5
source share

In the latest version of Angular, you need to use providers instead of injections, for example:

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

All Articles