I have Services set up in Angular to fetch JSON data from REST webservices. Now I consume data from service in OnInit method and store in local made array. But when I access them it shows undefined. Services are working fine, checked that data is coming or not. Sorry for bad english, not native language.
constructor(private myService: MyService, private anotherService: AnotherService) {}
arr: any[];
arr2: any[];
ngOnInit() {
this.myservice.getData(12).subscribe((data) => {
this.arr = data;
});
for (let item of this.arr) {
if (item.id == 5) {
this.arr2.push(item);
}
}
console.log('Data - ', this.arr2); // --> This shows undefined :(
}
But this works when I call custom method from OnInit
constructor(private myService: MyService, private anotherService: AnotherService) {}
arr: any[];
arr2: any[];
ngOnInit() {
this.myservice.getData(12).subscribe((data) => {
this.arr = data;
this.stage();
});
}
stage() {
for (let item of this.arr) {
if (item.id == 5) {
this.arr2.push(item);
}
}
console.log('Data - ', this.arr2); // --> This shows data :)
}
Someone help understand why. thanks