Angular 中的儿童父母沟通最佳实践 [英] child parent communication best practices in Angular

查看:19
本文介绍了Angular 中的儿童父母沟通最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力在 Angular 方面变得更好,我想了解亲子沟通之间的最佳实践.我当前想要开发的应用程序是 Angular 6.我知道我可以使用 @ViewChild、@Output 或创建服务在子父组件之间进行通信.有没有另一种方式进行通信?如果不是,这三个中哪一个更好,为什么?

这是一个简单的例子:

子 HTML

<button (click)="onLinkedClicked();">点击我</button>

儿童 TS

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';...导出类展示菜单组件实现 OnInit {@Output() public linkedClicked = new EventEmitter();构造函数(){}onLinkedClicked() {console.log('点击孩子');this.linkedClicked.emit('collapsed');}}

父 HTML

.</showcase-menu>

父 TS

<预><代码>...导航菜单状态:字符串;...linkToggler($event) {console.log("partent");this.navMenuState = $event;}

解决方案

显然这取决于你想做什么.

@Input

通过使用 @Input,您可以直接将参数传递给子组件.此外,您通过将一个组件放在另一个组件中来耦合组件.这种方法既实用又简单.

当您想要确保子组件集成到共享特定对象的父组件中并且您不必关心同步机制时,这是一种很好的方法.

也就是说,如果你改变了对象的一个​​属性,对象引用还是一样的,所以更新为父级和组件.但是如果你在一个组件中改变对象引用(例如实例化一个新的或通过远程服务检索一个新的对象),另一个组件无法检测到对象的变化,所以你会出现数据错位.

@Output

通过使用@Output,您将向上发出一个事件,因此当您想与父级沟通发生了某些事情时,此方法很有用.数据交换是可能的,但不是重点.

重点是发生了某些事情,例如在向导中您可以有一些步骤,并且每个步骤都可以通知父组件该特定步骤已完成.Parent 不需要知道是怎么发生的,只需要知道发生了什么,才能进入下一步.

@ViewChild

通过使用 @ViewChild,您可以将子组件引用导入父组件.

您通过混合逻辑来强制父组件使用特定的子组件.

当您想将子组件的某些方法调用到父组件中时,这很有用.

使用向导示例您可以考虑这种情况:

  • 我们有 3 个步骤
  • 第 3 步完成并向父级发出 @Output 事件
  • 父级捕获事件并尝试保存数据
  • 数据保存正常 => 父级告诉最后一步组件显示成功消息或
  • 数据保存失败 => 父级告诉最后一步组件显示失败消息

服务

通过使用外部服务,您将数据集中到一个负责管理和更新数据的外部对象中.

对于可以从远程服务检索数据或可以重新分配数据对象引用的情况,这是一种很好的方法.

此外,通过这种方法,您可以将所有组件彼此分离.他们可以工作而不必担心别人的行为.

一般Subject用于服务通信.

您可以在此处找到文档

主题 VS @Output

Subject 使用数据驱动的方法.@Output 使用事件驱动的方法,或者更好的 反应式编程 方法

同时,@Output 是您想要传达事件发生的首选方式,Subject 是传达数据已更改的首选方法.><块引用>

Subject 既是 observable 值的来源也是 Observable本身.您可以像订阅任何 Observable 一样订阅主题.

这意味着您可以使用 Subject 来观察特定的变量或值(Subject 作为 Observer),它检测观察到的值变化并发出某种事件.

与此同时,您可以让许多其他观察者通过订阅主题的事件来观察 Subject(Subject 作为 Observable).

当主题观察值发生变化时,通知所有主题的订阅者.

一个例子可能是票务应用程序.一位用户加载负责显示空闲剩余位置的组件.他正在考虑选择哪个地方.同时另一个用户买票,所以他的位置现在不可用.第一个用户现在应该看到那个地方不可用,因此您需要刷新数据,要求他们访问远程服务(可能使用轮询算法).当检索到新数据时,您将新数据传递到 Subject.next().Subject 检测到观察到的值已更改,并通知所有订阅者该值已更改.显然 Subject 将新数据传递给订阅者.

I'm trying to become better at Angular and I want to know the best practices between child-parent communication. My current app I want to work on is on Angular 6. I know I can communicate between child-parent components using @ViewChild, @Output or creating a service. Is there another way to do the communication? if not which one of those 3 is better and why?

Here's a simple example:

Child HTML

<button (click)="onLinkedClicked();">Click me</button>

Child TS

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
.
.
.
export class showcaseMenuComponent implements OnInit {
    @Output() public linkedClicked = new EventEmitter<String>();

    constructor() {}

    onLinkedClicked() {
        console.log('on click child');
        this.linkedClicked.emit('collapsed');
    }
}

Parent HTML

<showcase-menu #topNavMenu 
               [showBranding]="false"
               [showSearch]= "false"  
               (linkedClicked)="linkToggler($event)">. 
</showcase-menu>

Parent TS

.
.
.
 navMenuState: string;
.
.
.
  linkToggler($event) {
    console.log("partent");
    this.navMenuState = $event;
  }

解决方案

Obviously it depends on what you want to do.

@Input

By using @Input you are passing a parameter to a child component directly. Moreover you are coupling components by putting one inside the other. This approach is useful and simple.

It is a good approach when you want to ensure that a child component is integrated into a parent component that share a particular object and you don't have to care about synchronism mechanisms.

That means that if you change a property of the object, the object reference is still the same, so it is updated into parent and component. But if you change object reference (for example instantiating a new one or retrieving a new object by a remote service) in one component, the other one can't detect object change, so you will have a data misalignment.

@Output

By using @Output you are emitting an event upwards, so this approach is useful when you want to communicate to the parent that something is happened. Data exchange is possible but it is not the focus of the thing.

The focus is that something is happened, for example in a wizard you could have some step and each step can advise parent component that that particular step is completed. Parent does not need to know what how is happened, but only that is happened so it can go to the next step.

@ViewChild

By using @ViewChild you are getting child component reference into parent component.

You are forcing the parent to have a particular child component to work by mixing their logic.

This is useful when you want to call some method of the child component into the parent component.

Using the wizard example you can think about this situation:

  • we have 3 step
  • 3rd step completes and emits an @Output event to the parent
  • parent catches the event and tries to save data
  • data saving ok => parent tells last step component to show successful message or
  • data saving fail => parent tells last step component to show fail message

Service

By using an external service you are centralizing data into one external object that is responsible to manage and update data.

This is a good approach for situations in which data can be retrieven from remote services or data object references can be reassigned.

Moreover by this approach you are decoupling all your components from each other. They can work without worry themselves about others' behaviours.

Generally Subject are used into service communication.

You can find doc here

Subject VS @Output

Subject uses a data driven approach. @Output uses an event driven approach, or better a Reactive Programming approach

So meanwhile @Output is the preferred way when you want to communicate that an event is happened, Subject is the preferred approach to communicate that data are changed.

A Subject is both a source of observable values and an Observable itself. You can subscribe to a Subject as you would any Observable.

That means that you can use Subject to observe a particular variable or value (Subject as Observer), it detects observed value changes and emits a sort of event.

In the meanwhile you can have many other observer that are observing the Subject (Subject as Observable) by subscribing to subject's events.

When subject observed value changes, all subject's subscribers are advised.

An example could be a ticketing application. One user loads the component responsible of showing free remaining places. He is thinking on which place to choose. In the meanwhile another user buy a ticket, so his place is now unavailable. First user now should see that place as unavailable, so you need to refresh data asking them to remote services (maybe with a polling alghoritm). When new data are retrieven you pass new data into Subject.next(). Subject detects that observed value is changed and advices all his subscribers that the value is changed. Obviously Subject pass new data to subscribers.

这篇关于Angular 中的儿童父母沟通最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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