如何将角度8 http请求返回值保存在变量中? [英] how to save angular 8 http request return value in a variable?

查看:49
本文介绍了如何将角度8 http请求返回值保存在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我按如下所示以角度进行http呼叫:

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)

现在第一行中的console.log打印数据变量,并打印正确的返回结果,即json格式数据.我想做的是将返回值保存在 this.values 变量中,但不起作用. this.value 变量返回的对象中包含一些与我的返回值无关的奇怪信息.

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返回图片顶部的对象,而不是console.log(data)返回的底部json

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)

如何将http返回值保存到 this.value 变量中?

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

推荐答案

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

当您将 http.get 方法分配给值时,您正在分配对可观察对象本身的引用.您要调用可观察对象并更改订阅随附的回调中的值.

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.

这篇关于如何将角度8 http请求返回值保存在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆