[英]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.