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