对于组件交互,哪种方法最好@Input、@output 或使用服务

For component interaction which method is best @Input, @output or using service

我对 angular6.For 组件交互中的组件交互有一些疑问,我们有 @Input、@Output、viewChild 和服务等方法。但是大部分情况下我们都会用到服务。

  1. 在什么情况下我们需要在我们的应用程序中使用@Input、@Output和viewChild来传递值

  2. @Input、@Output 和 viewChild 方法有什么限制?

  3. 我们可以使用@Input、@Output 方法传递大量数据或值数组吗?

  4. 我们可以在本地范围内使用@Input 和@Output 吗? 请帮我解惑

@Input - From the Docs

The input property is bound to a DOM property in the template. During change detection, Angular automatically updates the data property with the DOM property's value.

当您的组件具有父子关系时,此方法很有用。这是将数据从父级传递给子级的简单方法。

根据文档,我们不需要在更新 Parent 变量时更改数据,这意味着在对象引用未更改之前无需担心同步。

@Output - From the Docs

The DOM property bound to the output property is automatically updated during change detection.

当您想通知父组件有关子组件中已完成的某些操作时,这种方法很有用。

您也可以将数据从子组件传递到父组件,但实际 use-case 是更改检测。当您想根据子组件操作在父组件中执行某些操作时。

@ViewChild - From the Docs

Property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes, and a new child matches the selector, the property is update.

当你想从子组件访问多个 属性 并且在 Angular 中我们可以通过组合在组件模板中定义普通 HTML 元素时很有用ViewChild.

如果您想在父组件中使用更多子属性来执行操作,那么它很有用。

服务 -- From the Docs

Services are a great way to share information among classes that don't know each other.

如文档中所述,当您希望跨多个组件共享数据并且它们之间不需要关系时,这些 类 很有用。

服务可以依赖于其他服务,通过使用外部服务,您可以将数据集中到一个负责管理和更新数据的外部对象中。

在最新 RxJS Libary you can centralize data in efficient way (for limited pint of time) with help of Subject and Behavior Subject.

的帮助下