I'm using subscribe which is asynchronous and so the counter variable is being returned before getting updated. Is there an alternative to subscribe that will allow me to only return the counter variable once its updated with the value gotten from the backend?
makeOffer(product: string, offer: number): number {
let formData = new FormData();
formData.append('name', product);
formData.append('offer', offer.toString());
let counter = 1
this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
.subscribe((data) => {
counter = data['counter']
}, (error) => {
console.log('Error! ', error)
});
return counter;
}
You need to use .map instead of .subscribe. Later is mainly used if you want the response updated to the DOM.
makeOffer(product: string, offer: number): Observable<number | null> {
let formData = new FormData();
formData.append('name', product);
formData.append('offer', offer.toString());
let counter = 1
return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
.map((data) => {
return data['counter']
}, (error) => {
console.log('Error! ', error);
return null;
});
}
Component:
this.service.makeOffer().subscribe((counter)=>{
console.log(counter);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With