简体   繁体   English

为什么组件没有从服务接收数据

[英]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.据我了解,使用 Observables 时有一个特定的顺序。

  1. create Observable --> private dataSubject = new Subject();创建 Observable --> private dataSubject = new Subject();
  2. call Observable --> subscribe();调用 Observable --> subscribe();
  3. execute Observable --> next();执行 Observable --> next();
  4. dispose --> unsibscribe();处置 --> unsibscribe();

StackBlitz 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.首先,始终小心取消订阅可在销毁时观察到的非 HTTP。
  • When you want to push a value to subject, you should give the value inside next() .当您想将值推送到主题时,您应该在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). (对于 Cleaner Code 是可选的),当 function 有副作用时,它不应返回值(将查询与命令分开)。

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.根据我在您的 stackblitz 示例中发现的内容,您在上述问题的第三部分中遇到了问题。

3. execute Observable --> next(); 3. 执行 Observable --> next();

You were not executing your observable all you needed to pass value to your Observable to execute你没有执行你的 observable 你需要将值传递给你的 Observable 来执行

What you are doing in your service (in stackblitz code example)您在服务中所做的事情(在 stackblitz 代码示例中)

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.在你的 stackblitz 示例中更新它,它现在应该可以工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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