简体   繁体   中英

Angular 4 - fetching data from Service and storing in Component

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

You need to move the code from outside the .subscribe() inside of it. The code inside the .subscribe() is asynchronous meaning the code below it gets executed straight away rather than waiting for the code inside the .subscribe() to complete.

The good old asynchronous call issue.

ngOnInit() {
 this.myservice.getData(12).subscribe(...);
 for (let item of this.arr) {...}
 console.log(...);
}

First line, you request data with an asynchronous call. Basically, put into words :

Go fetch data, and when you have it, do what I tell you to do in the subscribe.

Once this order is given, the code continues to be run.

This means that if your call takes 10 seconds to complete, Angluar won't wait 10 seconds before launching your for loop : it will run instantly .

That's why you don't see your data. It is outside of the subscribe function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM