1

I want to get index zero record from Array Object dataList in the below code snippet. I am new to JavaScript and Typescript.

dataList: Array<any> = [];
 data: any;

 constructor(private apiService: ApiService) {  


   this.apiService.getEncounterDashBoard(this.searchCond)
     .subscribe(data => {
       this.dataList = data.result;
     });

    let labels = this.dataList[0];
}
Sitansu
  • 3,225
  • 8
  • 34
  • 61
  • 3
    Put the line `let labels = this.dataList[0];` just after `this.dataList = data.result;`. The reason is `dataList` is updated asynchronously in a callback, meaning `this.dataList[0]` might not hold any data when you call it. – Prerak Sola Jun 04 '19 at 09:18
  • 3
    `.subscribe` is an async function. You will have to set `labels` inside `.subscribe` – Rajesh Jun 04 '19 at 09:19
  • Possible duplicate of [what is .subscribe in angular?](https://stackoverflow.com/questions/44921788/what-is-subscribe-in-angular) – wentjun Jun 04 '19 at 09:48

3 Answers3

2

you can try like this

dataList: Array<any> = [];
 data: any;

 constructor(private apiService: ApiService) {  

 let labels = [];
   this.apiService.getEncounterDashBoard(this.searchCond)
     .subscribe(data => {
       this.dataList = data.result;
       labels = this.dataList[0]; 
// here you can see that we are access the data inside the subscription block bcs javascript is asynchronous. So it is not wait complete the api call 
     });
}

Yash Rami
  • 2,276
  • 1
  • 10
  • 16
  • you should declare labels outside of the subscribe block, otherwise it can only be used inside. – djolf Jun 04 '19 at 09:21
0

Think of async operations as those that occur after the rest. Your getEncounterDashBoard is called and starts the request, but everything in your code continues, with or without response (usually without as everything is too quick).

Therefore, your let labels is trying to get this.dataList[0] before you actually have a response. One thing you can do, is create a component-scoped variable labels, and then asign it inside the callback of the async function (inside the subscribe), this way this happens after the async function has resolved.

Another option, is create a function that handles the logic you want to happen after the async is resolved, and call it inside the subscribe.

afterDataList() {
  let labels = this.dataList[0]
  // do something with it
  // ...
}
0

Place the line inside the subscribe function.

.subscribe(data => {
   this.dataList = data.result;
   let labels = this.dataList[0];
 });

You can also use ES6 destructuring:

.subscribe(data => {
   this.dataList = data.result;
   let [labels] = this.dataList;
 });
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79