Reputation: 61
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?
Upvotes: 0
Views: 1600
Reputation: 183
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
}
Upvotes: 0
Reputation: 10979
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);
Upvotes: 0