首页 > 解决方案 > 如何从可观察的 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 请求返回值的方法?

标签: angularhttpobservable

解决方案


更新

看来您只能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

}

推荐阅读