Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular alternative to subscribe?

Tags:

angular

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;
}
like image 788
Oblivion Avatar asked Sep 21 '25 02:09

Oblivion


1 Answers

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);
  });
like image 138
Suresh Kumar Ariya Avatar answered Sep 22 '25 16:09

Suresh Kumar Ariya