Angular alternative to subscribe?

Viewed 7712

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;
}
3 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);
  });

Unfortunatelly no. The corect way to address this problem is to return observable from the method and subscribe to it where you need it.

You can try using the map operator from Rxjs to transform the value the way you want it to be:

For Angular 4:

import 'rxjs/add/operator/map';

makeOffer(product: string, offer: number): Observable<number> {
  ...

  return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
    .map(data => data['counter']);
}

For Angular 5+

import { map } from 'rxjs/operators';

makeOffer(product: string, offer: number): Observable<number> {
  ...

  return this.http.post('http://localhost/Project/PHP/negotiation.php', formData)
    .pipe(map(data => data['counter']));
}

And then in your Component:

this.serviceName.makeOffer(...)
  .subscribe(counter => console.log(counter));
Related