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];
}
3
  • 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. Commented Jun 4, 2019 at 9:18
  • 3
    .subscribe is an async function. You will have to set labels inside .subscribe Commented Jun 4, 2019 at 9:19
  • Possible duplicate of what is .subscribe in angular? Commented Jun 4, 2019 at 9:48

3 Answers 3

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 
     });
}

Sign up to request clarification or add additional context in comments.

1 Comment

you should declare labels outside of the subscribe block, otherwise it can only be used inside.
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
  // ...
}

Comments

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;
 });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.