Within my component, there are several methods including constructor(){...}
and ngOnInit(){...}
. I have declared a variable named values:any=[]
in the class, and it is initialized with JSON data within a method called getData()
.
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
})
}
I then call this getData()
method in ngOnInit(){...}
. After this call, I observe that values
is indeed populated with data. However, when I try to access values
in another method for displaying purposes, it shows up as an empty array.
export class AccountComponent implements OnInit {
values:any=[];
constructor(private service: AccountService) {
}
getData(){
this.service.getData().subscribe(res=>{
this.values = res.json();
})
}
callData(){
console.log(this.values)
}
ngOnInit() {
this.getData();
this.callData();
}
In the callData()
method, I use console.log()
, which displays that values
is empty. But why does this happen?