简体   繁体   English

如何在Angular的同级组件之间传递数据?

[英]How can I pass data between sibling components in Angular?

I'm building an ecommerce app with Angular, I wonder how can I pass the total amount from the ShoppingCart component to the Checkout component. 我正在使用Angular构建一个电子商务应用程序,我想知道如何将购物车组件中的总金额传递给Checkout组件。 The two components are sibling. 这两个组成部分是同级的。 I saw few ways to do it, like BehaviourSubject and NavigationExtras but I don't know if they are good practice. 我看到很少的方法可以做到这一点,例如BehaviourSubject和NavigationExtras,但我不知道它们是否是好的做法。

You can use service for shared data. 您可以将服务用于共享数据。 If you have complex use case, that the data is used everywhere and many components can make changes, then manybe you should consider state management process like redux. 如果您有复杂的用例,那么数据随处可见,并且许多组件都可以进行更改,那么您应该考虑像redux这样的状态管理过程。

Matteo the best solution for me is used the Subject . Matteo对我来说最好的解决方案是使用Subject The logic are these: 逻辑是:

  1. Create the Subject in the father's ngOnInit() ( create the channel) 在父亲的ngOnInit()创建主题(创建频道)
  2. Pass the Subject to siblings ( sign in the siblings in the channel) 将主题传递给同级(在通道中登录同级)
  3. In sibling's ngOnInit() you can register the sibling in to the channel 在同级的ngOnInit()中,您可以将同级注册到通道中
  4. when you click on checkout yuou can notify the component that are listening in the channel with the total amout. 当您单击结帐时,yuou可以通知频道中正在监听的组件的总金额。
  5. destroy channel and unregister the component 销毁频道并注销组件

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

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