我如何从孩子到祖父之间交流? [英] How can I comunicate from child to grandfather component?

查看:98
本文介绍了我如何从孩子到祖父之间交流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2开发一个应用程序.在我的场景中,它包含三个组件:

I'm developing one application with Angular 2. In my scenario there are three components:

  • SearchComponent:此组件调用网络服务,并将结果注入SearchResultComponent.
  • SearchResultComponent:此组件将我的数据公开到一个表中.
  • EditComponent:此组件允许编辑我的数据.

SearchComponent 代码下面:

<form>
    ... there my form input
</form>

<!-- result is a property inside my SearchComponent class -->
<search-result [(value)]="result"></search-result>

SearchResultComponent 代码下面:

<div>
    <table>
        ... there is my table
        ... foreach row I have one edit component
        <tr>
            <td>data</td>
            <td>
                <edit></edit>
            </td>
        </tr>
    </table>
</div>

在我的 EditComponent 代码下面:

<form>
    ... There are edit inputs...
</form>

<button label="Salva" (click)="edit()"></button>

<edit [(documentId)]="id"></edit>

我的目标是,当我单击保存"按钮时,我将重新加载结果.

My goal is that when I click on save button I would reload my result.

我如何达到目标?

谢谢

推荐答案

至少有两种方法可以做到这一点.
1.选项:创建一个像@AsifKarimBherani建议的单例服务.

There are at least 2 ways to do this.
1. Option: Create a singleton service like @AsifKarimBherani suggested.

..单例模式是一种软件设计模式,它将类的实例化限制为一个对象.当仅需要一个对象来协调整个系统中的动作时,这很有用.

..The singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

在Angular 2+中的简单用例中,您可以通过在app.module.ts中仅提供服务来获得这样的结果(如果使用Angular中的标准文件/文件夹结构,CLI ).

In simple use cases in Angular 2+ you can achieve such result by providing the service only in the app.module.ts (If using the standard file/folder structure from Angular-CLI).

2.选项:使用 @Output 装饰器创建从孙子到父母的桥梁,以及从父母到祖父母的另一桥梁.

2. Option: Create a bridge from grandchild to parent and another bridge from parent to grandparent using @Output decorator.

子组件公开一个EventEmitter属性,通过该属性发生事件时发出事件.父级绑定到该事件属性并对这些事件做出反应.

The child component exposes an EventEmitter property with which it emits events when something happens. The parent binds to that event property and reacts to those events.

孩子的EventEmitter属性是一个输出属性,通常装饰有@Output装饰

The child's EventEmitter property is an output property, typically adorned with an @Output decoration

希望这给您一些想法.

这篇关于我如何从孩子到祖父之间交流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆