0

I want to send data from one component to another via service and followed this answer. The problem is, that the data never is received by the receiver component. I also tried the solution of that question. My other idea why there could be something wrong is that I call the important "commands" in a wrong order. As far as I understand there is a particular order when you work with Observables.

  1. create Observable --> private dataSubject = new Subject();
  2. call Observable --> subscribe();
  3. execute Observable --> next();
  4. dispose --> unsibscribe();

StackBlitz

I hope someone can clearify whether I got a wrong understanding of observalbes or if it is just mistake. Thank you!

SNnaKR
  • 17
  • 8

2 Answers2

0

You had a couple of errors in your solution.

  • First of all, always be careful to unsubscribe from a non HTTP observable on destroy.
  • When you want to push a value to subject, you should give the value inside next().
  • Be aware that after first subscription created, then you are always tracking the name and after each submit, the new value will appears on the screen
  • (Optional for Cleaner Code), when a function has side effects, it should not return a value (separate queries from commands).

I created a working example from your stack blitz here.

StPaulis
  • 2,844
  • 1
  • 14
  • 24
  • Thank you!!! The part with destroy in the service was new to me. So for clarification: In what situations should subscriptions be called like that? And what is exactly the advantage of that in comparsion to the "normal" .subscribe? – SNnaKR Aug 20 '20 at 10:43
  • When you have an HTTP call, angular take care to unsubscribe on her own. When you are subscribing to Observables to trace data, you should always unsubscribe. – StPaulis Aug 20 '20 at 10:57
0

From what I found in your stackblitz example you had issue in the 3rd part of what you above describe in your question.

3. execute Observable --> next();

You were not executing your observable all you needed to pass value to your Observable to execute

What you are doing in your service (in stackblitz code example)

sendName(name) {
  this.nameSubject.next(); // executing empty observable
  return name; // no need of this if you are setting value in observable
}

What you should be doing

sendName(name) {
  // notice passing name to observable to execute rather returning
  this.nameSubject.next(name); 
}

Update this in your stackblitz example it should work now.

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31