.share() with .subscribe() _isScalar is missing
16,312
.subscribe()
returns a Subscription
(allows to unsubscribe).
If you want an Observable
, don't use subscribe(...)
.
You can instead use map(...)
this.post = this.data.getPostById(this.postId).share().map(data => {
this.post = data;
})
Author by
eulercode
Updated on June 17, 2022Comments
-
eulercode almost 2 years
I am trying to use
share()
withsubscribe()
but got error message as follow. Initially, i started with subscribe. How can this be fix?My intention is to execute the logic in subscribe. Share is needed to prevent multiple call with async pipe.
Type 'Subscription' is not assignable to type 'Observable'.
Property '_isScalar' is missing in type 'Subscription'. (property) PostDetailPage.post: Observablethis.post = this.data.getPostById(this.postId).share().subscribe(data => { this.post = data; }, err => { console.log("Oops!"); })
-
Günter Zöchbauer over 6 yearsYou can use the
catch
(for the onError parameter) andfinally
(for onCompletion) operators instead. github.com/ReactiveX/rxjs/blob/master/src/operator/catch.ts -
eulercode over 6 yearsjust a sideline can u explain in which scenario should i use subscribe vs share. Because some say use subscribe some say use share with async pipe to prevent manual unsubscribe and multiple call. I am pretty confused on which is a better approach/practice.
-
Günter Zöchbauer over 6 yearsSubscribe and share aren't interchangeable in any way. Subscribe is actually executing the executable. Without subscribe, you won't get any values. There are alternative operators like
forEach
that also execute the observable, butshare
doesn't,share
just changes the behavior when subscribe is called multiple times on the same observable. (see also stackoverflow.com/questions/35141722/…) -
Günter Zöchbauer over 6 yearsDelegating the subscription/unsubscription to the
| async
pipe is usually a good idea. It also causes change detection to run every time a new value is emitted. If you need to add some filter, map, ... or other operator, you can still assign the result to a field (like the code in my answer or your question) and use this with| async
.