json - 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。
解决方案
Http Get 是异步调用,在 Get 方法完成之前返回 returnVal。您可以在异步调用中返回值或等待 promise 解决。例如:
this.http.get('http://localhost:8080/getAll').subscribe((response: Response) => {
returnVal = response.json();
return returnVal;
});
推荐阅读
- kotlin - RxJava: Issue with withLatestFrom operator when using in combination with .subScribeOn
- swift - How to deal with NaN in large arrays using swift
- jmeter - 仪表板报告 - 事务/秒
- c - 为什么要为同名的函数定义宏?
- pandas - 将第二个条目保留在数据框中
- vector - 如何将两个 Rust 向量交织成一个新向量?
- http - 单页应用程序的简单命令行 http 服务器
- javascript - How to create a different random number for every single div with React on onclick event?
- javascript - 绝对定位一个 div 并隐藏页面的其余部分
- algorithm - 快速排序的平均情况