You try to read this.dataList
immediately after the call to this.service.getName()
but you have an ordering problem. Consider the following piece of code :
this.service.getName().subscribe(() => console.log('A'));
console.log('B')
This will display B A
because the call to this.service.getName()
is asynchronous.
What happens is :
- Call
this.service.getName()
- Call
console.log('B')
- Browser get the response from
this.service.getName()
and executes () => console.log('A')
Because of that, you try to read this.dataList
too soon, when it is still empty or undefined
. You should read its value inside the callback :
this.service.getName().subscribe((success: any) => {
if (success) {
for (let i = 0; i < success[i].length; i++) {
if (success[i].data.empid== data) {
this.dataList.push(success[i].name);
}
}
// Here, you can safely read this.dataList
[...]
}
});