首页 > 解决方案 > Angular - 如何获取 http get 请求的 json 值?

问题描述

所以我正在尝试设置一个非常基本的应用程序,让 localhost 上的 Angular 项目从 localhost 上的另一个项目中获取 json。

我有一个方法的服务

get() {
    var returnVal;
    this.http.get('http://localhost:8080/getAll).subscribe((response: Response) => returnVal = response.json())
return returnVal;
}

这将返回未定义,并且当我的 sub.component.ts 将它分配给一个变量时,它不会在 html 上显示任何内容,而它应该返回 json。

标签: jsonangular

解决方案


Http Get 是异步调用,在 Get 方法完成之前返回 returnVal。您可以在异步调用中返回值或等待 promise 解决。例如:

this.http.get('http://localhost:8080/getAll').subscribe((response: Response) => {
  returnVal = response.json();
  return returnVal;
});

推荐阅读