【问题标题】:What are the difference between the technics to pass data from components to others in Angular2?Angular 2 中将数据从组件传递给其他组件的技术有什么区别?
【发布时间】:2016-12-30 20:12:54
【问题描述】:

我想知道为什么 Angular2 中的组件之间有不同的技术来共享数据,如下所述:https://angular.io/docs/ts/latest/cookbook/component-communication.html

例如,“输入绑定”非常好用。为什么我会费心“父母和孩子通过服务进行交流”?

是否存在性能问题?或者它们是完全一样的,只取决于如何更容易维护。

谢谢,

【问题讨论】:

    标签: angular components


    【解决方案1】:

    输入绑定用于直系家庭(父母 - 孩子),而您可以将服务用于其他关系。我相信这是一种设计选择。

    就像这里一样,他们都可以交流,因为他们正在“接触”对方(哇,这太奇怪了):

    <parent>
      <child/>
    </parent> 
    

    在这里你可以使用输入、输出,它又快又优雅。

    在哪里

    <parent>
     <child>
      <subchild></subchild>
     </child>
     <otherChild>
       <otherSubChild></otherSubChild>
     </otherChild>
    </parent>
    

    在这里,如果您想从 otherSubChild 与 subChild 进行通信,您将使用服务,因为它们没有密切相关。

    不过,兄弟交流有一个巧妙的技巧:Catch event in sibling component

    <parent (event)="sis.onEvent">
      <bro/> <-- this is the guy emitting the event
      <sis #sis/>
    </parent> 
    

    也就是说,只要他们“感动”(上帝,我需要一个更好的词),彼此就不必依赖服务。

    【讨论】:

    • 谢谢。你认为应该用服务来让“兄弟”交流吗? ?
    • @JohnDoetheDoe 我编辑了我的回复,这就是你所说的兄弟交流的意思吗?几天前我实际上问了同样的问题:)
    猜你喜欢
    • 1970-01-01
    • 2018-12-11
    • 2021-08-15
    • 2017-08-30
    • 2017-06-15
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多