Search code examples
angularhttphttpclient

how to save angular 8 http request return value in a variable?


Im making a http call in angular as follows:

this.values = this.http.get("https://reqres.in/api/users/2").subscribe(data => console.log(data))
console.log(this.values)

now the console.log in the first line, which prints the data variable, prints the right return result, which is json format data. what im trying to do, is save that return value in the this.values variable, but its not working. this.value variable is returning an object of some weird information that has nothing to do with my return values.

The image below shows the console logs:

this.values returns the object at the top of the picture instead of the json at the bottom which is returned by console.log(data)

how can i save the http return value into this.value variable?


Solution

  • this.http.get("https://reqres.in/api/users/2").subscribe(data => {
      console.log(data);
      this.values = data;
    }
    

    when you assign the http.get method to values, you're assigning a reference to the observable itself. you want to call the observable and change the value inside the callback that comes with subscribe.