Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4: Update Component View after Async Call to Server

I am attempting to update my component's view after a service call is made during the ngOnInit lifecycle hook. I subscribe to the service method, and then in the subscription method, iterate through the response to create a ToDo object, where I then push that to the list. However, after this has been executed, it appears that the todoList is never updated. Any ideas?

Here is the component typescript code:

    export class CanvasComponent implements OnInit{
todo: ToDo;
todoList: ToDo[] = [];
tasks: Task[];

errorMessage: string;

constructor(public taskService: TaskService) {

}
ngOnInit(){
    // this.todo = new ToDo(0, 'placeholder', false, 'Please Implement custom components!');
    // this.newTodo = new ToDo(0, 'placeZholder', false, 'Please Implement custom components!');
    this.taskService.GetAll()
        .subscribe(response => {
            this.todoList = response;
        )
    }

..and my component view prints the information with this block:

<div class="row">
    <div *ngFor="let todo of todoList">
        {{todo.title}}
        {{todo.description}}
    </div>
 </div>
like image 856
Justlegos Avatar asked Sep 15 '17 06:09

Justlegos


2 Answers

Try to call get all method in the constructor level

constructor(public taskService: TaskService) {
   this.taskService.GetAll();
}
like image 163
Natarajan Nagarajugari Avatar answered Oct 23 '22 08:10

Natarajan Nagarajugari


I don't know how is your Todo/Task object built but here's this Plunker so i hope it helps you, i tried to do it as similar to your code as possible. double check what are you returning from your getAll() method and your service.

you probably want to return something like Observable<Task[]>, or whatever you want to return. Hope it helps you

like image 23
Alejandro Camba Avatar answered Oct 23 '22 06:10

Alejandro Camba