1

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

2 Answers 2

2

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.

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

4 Comments

If I use AfterContentInit will it resolve issue or have to put rest code inside subscribe ?
You need to put your code into a function that will be launched in your subscribe, just like you did when you made it work.
AfterContentInit is a lifecycle hook, it has nothing to do with HTTP calls.
Okay. Thanks for your solution
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.