I have a Url http://localhost:3000/users/1
that will return json:
{ "id": 1, "name": "David", "is_available": true }
then I want to make a method that return is_available (boolean). But this method below will return undefined. This seems weird for me that new to angular & observable.
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. How to properly create method that return value from http request?
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
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
this.checkIsAvailable(id).then((res) => {
console.log(res);
// your code here
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.