list.component
import { Component, OnInit } from '@angular/core';
import { Todo } from '../model/todo';
import { TodoDetailComponent } from './detail.component';
import { TodoService } from '../service/todo.service';
@Component({
selector: 'my-todos',
styleUrls: ['/app/todo/styles/list.css'],
templateUrl:'/app/todo/templates/list.html',
directives: [[TodoDetailComponent]],
providers: []
})
export class ListComponent implements OnInit {
public todos: Todo[];
title = 'List of Todos';
selectedTodo: Todo;
newTodo: string;
constructor(private todoService: TodoService) {
}
ngOnInit() {
this.getTodos();
}
addTodo() {
this.todoService.addTodo(this.newTodo).then(
todos => this.todos = todos
);
}
getTodos() {
TodoService.getTodos().then(
todos => this.todos = todos
);
}
onSelect(todo: Todo) {
this.selectedTodo = todo;
}
}
todo.service
import { Injectable } from '@angular/core';
import { Todo } from '../model/todo';
import { TODOS } from './mock-todos';
@Injectable()
export class TodoService {
static getTodos() {
return Promise.resolve(TODOS).then(
todos => todos
);
}
getTodo(id: number) {
return Promise.resolve(TODOS).then(
todos => todos.filter(todo => todo.id === id)[0]
);
}
addTodo(task: string) {
return Promise.resolve(TODOS).then(
todos => todos.push(new Todo(TODOS.length+1, task))
);
}
}
An issue arises when I attempt to invoke the addTodo()
function from the component:
I have inspected my code multiple times and am still unable to identify the root cause.
This is the definition of TODOS
:
import { Todo } from '../model/todo';
export var TODOS: Todo[] = [
{ id: 1, task: 'Do something' },
{ id: 2, task: 'Do something else' }
];
A button in the template triggers the execution of the addTodo()
method.