8

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!");
      })
eulercode
  • 1,107
  • 4
  • 16
  • 29

1 Answers1

16

.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;
  }) 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • You can use the `catch` (for the onError parameter) and `finally` (for onCompletion) operators instead. https://github.com/ReactiveX/rxjs/blob/master/src/operator/catch.ts – Günter Zöchbauer Sep 14 '17 at 06:33
  • 1
    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. – eulercode Sep 14 '17 at 06:38
  • 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 https://stackoverflow.com/questions/35141722/how-does-the-rxjs-5-share-operator-work) – Günter Zöchbauer Sep 14 '17 at 06:42
  • 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`. – Günter Zöchbauer Sep 14 '17 at 06:44