Angular4: update component view after asynchronous call to server

I am trying to update the component view after a service call during the ngOnInit life cycle. I subscribe to the service method, and then in the subscribe method iterate through the response to create a ToDo object, where I then drag it to the list. However, after this was done, it turned out that todoList was never updated. Any ideas?

Here is the typescript component 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 information with this block:

<div class="row">
    <div *ngFor="let todo of todoList">
        {{todo.title}}
        {{todo.description}}
    </div>
 </div>
+4
source share
3 answers

, GetAll() , ".data" response.json().

, :

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

.data:

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

, , todoList , undefined. , , .

!

0

get

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

I don’t know how your Todo / Task object was created, but here is this Plunker , so I hope this helps you, I tried to make it as close as possible to your code. double check that you are returning from the getAll () method and your service.

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

+1
source

Source: https://habr.com/ru/post/1685720/


All Articles