1

This function with get / http / subscribe does not return the correct value, it returns undefined, why?`

function_one() {
    let text = this.getData();
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        return response;
      }
      );
  }

3 Answers3

1

You'll need to return your observable and subscribe to it in order to get the value.

Try this:

function_one() {
    this.getData().subscribe((text) => {
        // Do something with text
        console.log('Your text will appear', text);
    });

}

getData() {
    return this.http.get("assets/img/tutorial/tutorialenus.JSON");
}
Damian C
  • 2,111
  • 2
  • 15
  • 17
1

without seeing the rest of the code: I would recommend this:

getData() {
  //return observable
  return this.http.get("assets/img/tutorial/tutorialenus.JSON");
}

function_one() {
  //subscribe to and log observable response data
  this.getData().subscribe
  (response => {
    console.log(' Here response = The simple text', response);
  }
}
Don Thomas Boyle
  • 3,055
  • 3
  • 32
  • 54
0

The HTTP get function is asynchronous. So it wont return data to function_one(). To fix this, instead of having function_one() call getData(), have getData() call function_one().

Like this

  function_one(text) {        
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        this.function_one(response)
      });
  }
William Stevens
  • 514
  • 6
  • 9