My angular SPA doesn't refresh when my EventEmitter emits an event.
Here is my EventEmitter
in the child component:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { Todo } from '../todo';
@Component({
selector: 'app-add-todo',
templateUrl: './add-todo.component.html',
styleUrls: ['./add-todo.component.css']
})
export class AddTodoComponent implements OnInit {
newTodo: Todo = new Todo();
@Output() addTodoEvent: EventEmitter<Todo> = new EventEmitter();
constructor() { }
addTodo() {
this.addTodoEvent.emit(this.newTodo);
console.log('event emitted');
this.newTodo = new Todo();
console.log('new todo created');
}
ngOnInit() {
}
}
Here is the template that consumes it:
<div class="container">
<app-add-todo (addTodoEvent)='onAddTodo($event)'></app-add-todo>
// other template stuff
</div>
Here is the declaration of onAddTodo
:
onAddTodo(todo: Todo) {
console.log('onAddTodo called');
this.todoDataService.addTodo(todo);
}
Basically, the application works, but I have to hit F5 to refresh the page after any change is made.
One thing to note is that this used to work when I was using an array as a data source, but when I went to json-server and Observables, the page stopped refreshing.
I'm happy to supply any further information that may be needed.
UPDATE:
Here's addTodo
:
addTodo(todo: Todo): void {
this.aHttpService.post<Todo>(`http://localhost:3000/todos`, todo).subscribe(
val => {
console.log('POST call successful value returned in body', val);
},
response => {
console.log('POST call in error', response);
},
() => {
console.log('The POST observable is now completed.');
}
);
}
The full code to list the todos is as follows:
import { Component, OnInit } from '@angular/core';
import { Todo } from '../todo';
import { TodoDataService } from '../todo-data.service';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent implements OnInit {
constructor(private todoDataService: TodoDataService) {}
completetodos: Observable<Array<Todo>>;
incompletetodos: Observable<Array<Todo>>;
onAddTodo(todo: Todo) {
console.log('onAddTodo called');
this.todoDataService.addTodo(todo);
}
toggleTodoComplete(todo) {
this.todoDataService.toggleTodoComplete(todo);
}
removeTodo(todo) {
this.todoDataService.deleteTodoById(todo.id);
}
editTodo(todo: Todo) {
todo.editMode = true;
}
updateTodo(todo: Todo, editInput) {
todo.title = editInput.value;
todo.editMode = false;
this.todoDataService.updateTodoById(todo.id, todo);
}
allTasks(): Observable<Array<Todo>> {
return this.todoDataService.getAllTodos();
}
completedTodos(): Observable<Array<Todo>> {
return this.todoDataService.completedTodos();
}
incompletedToDos(): Observable<Array<Todo>> {
return this.todoDataService.incompletedTodos();
}
ngOnInit() {
this.completetodos = this.completedTodos();
this.incompletetodos = this.incompletedToDos();
}
}
addToDo
call.