Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular RXJS get data without subscribing

Tags:

angular

rxjs

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);
like image 228
Omar Avatar asked Oct 28 '25 03:10

Omar


1 Answers

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();
like image 156
William Lohan Avatar answered Oct 30 '25 11:10

William Lohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!