简体   繁体   中英

Why does component not receive data from service

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!

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM