[英]how to return value from observable http request and store it in local variable?
我有一個 Url http://localhost:3000/users/1
將返回 json:
{ "id": 1, "name": "David", "is_available": true }
然后我想創建一個返回is_available (布爾值)的方法。 但是下面的這個方法將返回未定義。 這對我來說似乎很奇怪,對於 angular 和可觀察到的新手。
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 請求返回值的方法?
checkIsAvailable(id): Observable<boolean>{
let available;
return http.get('http://localhost:3000/users/1').pipe(map(user => {
return user.is_available;
}));
}
訂閱組件
this.service.checkIsAvailable().subscribe((res)=>this.available = res);
更新
看來您只能從異步 function 返回Promise
嘗試以下
async checkIsAvailable(id): Promise<any> {
return await http.get('http://localhost:3000/users/1').toPromise();
}
改變你稱之為 function 的方式
this.checkIsAvailable(id).then((res) => {
console.log(res);
// your code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.