6

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>
Justlegos
  • 81
  • 7
  • 2
    Sounds like the `taskService.GetAll()` calls out to some non-Angular code. Can you please add this code as well to your question? See also https://stackoverflow.com/questions/36919399/angular-2-view-not-updating-after-model-changes/36919459#36919459. In your case `zone.run()` might be a good idea, but it should best be used as close as possible to the code that exits Angulars zone instead of on random locations where this breaks your app. – Günter Zöchbauer Sep 15 '17 at 06:24

3 Answers3

1

Try to call get all method in the constructor level

constructor(public taskService: TaskService) {
   this.taskService.GetAll();
}
1

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

Alejandro Camba
  • 978
  • 10
  • 25
0

Alright, it turns out in my GetAll() method from my service, I had forgot to call the ".data" attribute after I was calling response.json().

So here is what I originally had:

return this.http.get(this.url)
         .map( response => {
             this.tasks = response.json();
             return this.tasks;
});

Where what fixed the issue was adding the .data attribute here:

return this.http.get(this.url)
         .map( response => {
             this.tasks = response.json().data;
             return this.tasks;
});

As a result, when I was trying to perform my subscribe method, where I set the todoList to the response, I was getting an undefined error. With this fixed however, that resulted in the information finally displaying properly.

Thanks for the help everyone!

Justlegos
  • 81
  • 7