.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;
  }) 
Share:
16,312
eulercode
Author by

eulercode

Updated on June 17, 2022

Comments

  • eulercode
    eulercode almost 2 years

    I am trying to use share() with subscribe() 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: Observable

     this.post = this.data.getPostById(this.postId).share().subscribe(data => {
              this.post = data;
          },
          err => {
              console.log("Oops!");
          })
    
  • Günter Zöchbauer
    Günter Zöchbauer over 6 years
    You can use the catch (for the onError parameter) and finally (for onCompletion) operators instead. github.com/ReactiveX/rxjs/blob/master/src/operator/catch.ts
  • eulercode
    eulercode over 6 years
    just 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
    Günter Zöchbauer over 6 years
    Subscribe 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, but share 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
    Günter Zöchbauer over 6 years
    Delegating 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.