user4207046
user4207046

Reputation:

Angular 2 No provider error

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?

Upvotes: 10

Views: 26603

Answers (2)

sachinkasana
sachinkasana

Reputation: 71

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

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

Upvotes: 1

Brocco
Brocco

Reputation: 64883

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.

Upvotes: 9

Related Questions