简体   繁体   English

如何从可观察的 http 请求中返回值并将其存储在局部变量中?

[英]how to return value from observable http request and store it in local variable?

I have a Url http://localhost:3000/users/1 that will return json:我有一个 Url http://localhost:3000/users/1将返回 json:

{ "id": 1, "name": "David", "is_available": true }

then I want to make a method that return is_available (boolean).然后我想创建一个返回is_available (布尔值)的方法。 But this method below will return undefined.但是下面的这个方法将返回未定义。 This seems weird for me that new to angular & observable.这对我来说似乎很奇怪,对于 angular 和可观察到的新手。

checkIsAvailable(id): boolean {
        let available;
        http.get('http://localhost:3000/users/1').subscribe(user => {
                available = user.is_available;
        }
        return available;
}

If I console.log() inside the.subscribe(), user.is_available will return true.如果我在.subscribe() 中使用console.log(), user.is_available将返回true。 How to properly create method that return value from http request?如何正确创建从 http 请求返回值的方法?

checkIsAvailable(id): Observable<boolean>{
        let available;
        return http.get('http://localhost:3000/users/1').pipe(map(user => {
                return user.is_available;
        }));
}

Subscribe in component订阅组件

this.service.checkIsAvailable().subscribe((res)=>this.available = res);

UPDATE更新

it seems you can only return Promise from an async function看来您只能从异步 function 返回Promise

try the following尝试以下

async checkIsAvailable(id): Promise<any> {
        return await http.get('http://localhost:3000/users/1').toPromise();
}

change the way you call this function改变你称之为 function 的方式

this.checkIsAvailable(id).then((res) => {
  console.log(res);

  // your code here

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 http 请求返回 observable - How to return an observable from http request 如何在变量中保存 angular 8 http 请求返回值? - how to save angular 8 http request return value in a variable? 如何将 observable 中的值存储在 aa 变量或属性中 - How to store values from an observable in a a variable or property 从http请求的订阅角度返回对象的可观察对象 - Return observable of object from subscribe of an http request angular 我应该如何修改对 HTTP 请求的响应并在从 Observable 返回之前轻松访问它? - How should I modify the response to an HTTP request and easily access it before return it out from Observable? 如何从Observables值构造数据,并返回一个Observable <Response> 在HTTP呼叫之后? - How to construct data, from Observables value, and return a Observable<Response> after the HTTP call? 从 http Post 返回 Observable - Return Observable from http Post 从HTTP请求订阅Observable - Subscribing Observable from HTTP request 如何通过在组件内部订阅变量来从可观察值存储值-Angular4 - How to store value from observable via subscribe to variable inside component - Angular4 如何在Angular 2中将值从可观察值设置为变量 - How to set a value from observable to a variable in Angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM