0

I'm trying to pass data using http.get from a JSON to other component, but always I get a "undefined"

In my service.ts I have the getDate function

getData(): Promise<MinnanoNihongo[]>{
   return this.http.get("../../assets/json/leccion1.json")
          .toPromise()
          .then(response => response.json().data as MinnanoNihongo[]);
}

And in my component I call using:

this.MinnaData
         .getData()
         .then( data => this._Minna = data );
    console.log(this._Minna);  //show Undefined in console

I'm new using Angular and typescript so I don't know what produce the problem.

Devjoks
  • 42
  • 8

2 Answers2

1

It's because console.log(this._Minna); is executed before .then( data => this._Minna = data );

Try

this.MinnaData
         .getData()
         .then( data => this._Minna = data ).then(() => {
             console.log(this._Minna)
         });
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
0

You should print console.log inside then

this.MinnaData
         .getData()
         .then( (data) => {this._Minna = data;
          console.log(this._Minna);
 });
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396