angularangular6angular-arrays

Angular service code is running with a delay


I am new to angular. Learning Angular 6. Trying to fetch data from a database which is working totally fine. But I am trying to get the length of the returned array also. Problem is the code for getting the length is being executed before the array can return. So it is showing undefined.

Can anyone help me with this ? What is wrong with this code ?

listItems: any;

constructor(private crud_data: CrudserService) { }

ngOnInit() {
this.crud_data.get_the_list().subscribe(
res => this.listItems = res
);
this.todolist_count = this.listItems.length;
}

Solution

  • Just do this:

    ngOnInit() {
      this.crud_data.get_the_list().subscribe(res => { 
        this.listItems = res;
        this.todolist_count = this.listItems.length;
      });
    }