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);
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();
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