1

So I have this Service in Angular2

fetchData(){
    return this.http.get('https://ng-workout.firebaseio.com/Workouts/.json').map(
        (res) => res.json()
    );
}

And then this Component

export class HomeComponent  {

workouts = [];

constructor(private dataService: DataService){
}

ngOnInit(){
this.dataService.fetchData().subscribe(
    data=> this.workouts =data
    );
    console.log(this.workouts);
    }
}

So the thing is, when i console log 'this.workouts' it returns 0, an empty array. Shouldn't there be all the records from the json file?

raulnoob
  • 119
  • 1
  • 1
  • 7

1 Answers1

1

You need to move the console.log() code into the callback you pass to subscribe

ngOnInit(){
  this.dataService.fetchData().subscribe(
    data=> {
      this.workouts =data;
      console.log(this.workouts);
    });
}

fetchData (observables) are async. The function you pass to subscribe is executed when data becomes available.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Ok, but if i want to work with the workouts array on another page, every time i want info from the array i have call the subscribe? – raulnoob Feb 14 '17 at 10:25
  • Perhaps http://stackoverflow.com/questions/36271899/what-is-the-correct-way-to-share-the-result-of-an-angular-2-http-network-call-in/36291681#36291681 is what you want. – Günter Zöchbauer Feb 14 '17 at 10:31