10

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?

P.S.
  • 15,970
  • 14
  • 62
  • 86

2 Answers2

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.

Brocco
  • 62,737
  • 12
  • 70
  • 76
  • Thanks for this. I am doing exactly the same thing. However, my app is crashing at the "injectables: " line. Because the TodoService hasn't loaded, it loads later.. If I declare it in the same file its fine, but if its in a separate file it comes later. How can I avoid this? – williamsandonz May 27 '15 at 06:08
  • You can probably use @InjectPromise in the constructor; see angular2.src.di.annotations_impl – Sanford Redlich Jun 14 '15 at 17:04
  • 5
    check this answer for newer angular http://stackoverflow.com/questions/30580083/angular2-no-provider-for-nameservice – Peter Sep 08 '15 at 08:26
1

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

@Component({
    selector: 'my-app',
    providers: [TodoService]
})
Rob
  • 26,989
  • 16
  • 82
  • 98