3

I have this function in a service to get data from my API

getProductById(id) {
    return this.http.get<any>(piUrl + '/id', { params: id }).catch(this.errHandler);
}

the only way i know how to get the data in my component is to subscribe like this.

this.myService.getProductById(id).subscribe(product => this.product = product);

but i just need the data once there is no stream. How can i get the data once? Something like this.

this.myService.getProductById(id).once(product => this.product = product);
Omar
  • 2,726
  • 2
  • 32
  • 65
  • look for example here https://stackoverflow.com/questions/28007777/create-one-time-subscription/28030416#28030416 – Roman Šimík Dec 05 '18 at 18:22
  • 1
    Or you can pass directly observable through async pipe eg. [angular.io](https://angular.io/api/common/AsyncPipe) – jakubm Dec 05 '18 at 18:24

1 Answers1

6

The RXJS 5-6 way would be

this.myService.getProductById(id).pipe(
 first()
).subscribe(product => this.product = product);

or

this.myService.getProductById(id).pipe(
 take(1)
).subscribe(product => this.product = product);

but this does nothing and is not needed because HttpClient.get() returns a self completing observable that emits once and completes, the subscribe callback will only ever run once. So this doesn't change the behavior at all.

If you prefer you could also

this.myService.getProductById(id).toPromise().then(product => this.product = product);

or

this.product = await this.myService.getProductById(id).toPromise();
Wilhelmina Lohan
  • 2,803
  • 2
  • 29
  • 58
  • Thanks for the explanation! – Mickers Dec 05 '18 at 19:01
  • what is the benefit of a promise over a one time observable? do i need to unsubscribe from one time observables? – Omar Dec 06 '18 at 03:06
  • At that point its mostly different syntax, although you could say the benefit of Promise is being able to use async await and Oberservable being able to unsubscribe before the request is complete to "cancel". No you do not need to unsubscribe from self completing observables. – Wilhelmina Lohan Dec 06 '18 at 16:22