angular - 如何从可观察的 http 请求中返回值并将其存储在局部变量中?
问题描述
我有一个http://localhost:3000/users/1
将返回 json 的 URL:
{ "id": 1, "name": "David", "is_available": true }
然后我想创建一个返回is_available(布尔值)的方法。但是下面的这个方法将返回未定义。这对我来说似乎很奇怪,对于角度和可观察的新手。
checkIsAvailable(id): boolean {
let available;
http.get('http://localhost:3000/users/1').subscribe(user => {
available = user.is_available;
}
return available;
}
如果我在 .subscribe() 中使用 console.log(),user.is_available将返回 true。如何正确创建从 http 请求返回值的方法?
解决方案
更新
看来您只能Promise
从异步函数返回
尝试以下
async checkIsAvailable(id): Promise<any> {
return await http.get('http://localhost:3000/users/1').toPromise();
}
改变你调用这个函数的方式
this.checkIsAvailable(id).then((res) => {
console.log(res);
// your code here
}
推荐阅读
- neo4j - Neo4J 负载分布
- c# - Xamarin 表单中的选取器 SelectedItem 绑定问题
- python - 删除内容后如何设置 tkinter 条目验证
- microservices - 如何解决事件存储和持久层之间的两个通用问题?
- video-streaming - Shaka 播放器一首曲目自动播放循环 - 永远流式传输而不是一次
- wordpress - 在现场看不到的图像在本地工作正常
- powershell - PowerShell New-ADComputer 二进制属性
- oracle - JDBC:像过程一样调用 Oracle 函数
- image - Flutter 图像裁剪和变换。
- rxjs - Observer.error 没有发送错误