0

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;
}
Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
  • check with in the subscribe...oninit your initializing the data call as well as count of length at a time – Sa E Chowdary Jul 23 '18 at 10:27
  • *"is being executed before the array can return"* - of course it is. When you `subscribe` you set up a callback to get executed *later*, when the asynchronous request is completed. There is no way the list items will be available before then. – jonrsharpe Jul 23 '18 at 10:29
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Jul 23 '18 at 10:29
  • @jonrsharpe how do I achieve that then ? I know how it works in jqyery ajax. I just don't know how to do with the angular. – Shubhajit Halder Jul 23 '18 at 10:38
  • @SaEChowdary this is what I am doing with the service.ts get_the_list() { return this.http.get(this.all_fetch_url); } I know I have to change something in the subscribe function. But I don't know what. This is my 2nd day with Angular. – Shubhajit Halder Jul 23 '18 at 10:41
  • no worry man just upside down these two lines ); this.todolist_count = this.listItems.length; like this.todolist_count = this.listItems.length;); – Sa E Chowdary Jul 23 '18 at 10:44

1 Answers1

0

Just do this:

ngOnInit() {
  this.crud_data.get_the_list().subscribe(res => { 
    this.listItems = res;
    this.todolist_count = this.listItems.length;
  });
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sidhanshu_
  • 1,714
  • 1
  • 7
  • 10