简体   繁体   English

Angular 1.5。 组件通信。 最佳实践

[英]Angular 1.5. Components communication. Best practice

I'm using Angular 1.5.9. 我正在使用Angular 1.5.9。

Right now I have two components which need to communicate. 现在我有两个需要沟通的组件。 If I change something in the first one (for example choose item in the list) => second one needs to be changed (item that was chosen needs to be displayed) and vice versa (changing in the second one => change in the first one) I have read about a lot of approaches, so I can manage this in few ways: 如果我在第一个中更改某些内容(例如,在列表中选择项目)=>第二个需要更改(需要显示所选项目),反之亦然(在第二个中更改=>在第一个中更改一)我已经阅读了很多方法,所以我可以通过几种方式来解决这个问题:

  1. Communication via shareable Service 通过可共享服务进行通信
  2. Using two way data binding ("=" option in component bindings). 使用双向数据绑定(组件绑定中的“=”选项)。 Example: https://jsfiddle.net/peter_drinnan/t4q4nrfp/27/ 示例: https://jsfiddle.net/peter_drinnan/t4q4nrfp/27/https://jsfiddle.net/peter_drinnan/t4q4nrfp/27/
  3. Using one way data binding with input/output approach. 使用单向数据绑定与输入/输出方法。 Example: http://stackoverflow.com/questions/36033940/how-to-pass-data-between-child-components-in-angular-1-5-not-using-scope 示例: http://stackoverflow.com/questions/36033940/how-to-pass-data-between-child-components-in-angular-1-5-not-using-scopehttp://stackoverflow.com/questions/36033940/how-to-pass-data-between-child-components-in-angular-1-5-not-using-scope
  4. Using "require" (some parent component to share data). 使用“require”(某些父组件共享数据)。 Example: http://stackoverflow.com/questions/36645065/component-communication-in-angular-1-5 示例: http://stackoverflow.com/questions/36645065/component-communication-in-angular-1-5http://stackoverflow.com/questions/36645065/component-communication-in-angular-1-5

Maybe I miss something? 也许我想念一些东西? What is the best practice? 什么是最佳做法?

Thank you. 谢谢。

Your whole example is perfect for using 3 option: 您的整个示例非常适合使用3选项:

  1. parent component to load/save data 父组件加载/保存数据
  2. Component to show list with callback on select 用于在select上显示回调列表的组件
  3. Component to show(+edit) 要显示的组件(+编辑)

This way will give you easy testability and etc. (Please take a look at benefit list ) 这种方式将为您提供简便的可测试性等(请查看福利清单

What is interesting for me is how to communicate between not so close components: 对我来说有趣的是如何在不那么紧密的组件之间进行通信:

We have component A to show cities and component B to show Countries each load data for itself, and trick is - when you delete last city from country (A) you need to remove country from a list (C). 我们有组件A显示城市和组件B显示国家每个加载数据本身,并且技巧是 - 当你从国家(A)删除最后一个城市时,你需要从列表中删除国家(C)。 Assume that we need to reload list of countries... 假设我们需要重新加载国家/地区列表...

What is best practice to communicate in this case? 在这种情况下,沟通的最佳做法是什么?

I have a strong feeling that events using $rootScope is bad way to go... 我有一种强烈的感觉,使用$ rootScope的事件是不好的方式...

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

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