【问题标题】:Angular 10 async bidirectional inter component comunicationAngular 10 异步双向组件间通信
【发布时间】:2021-04-13 11:06:40
【问题描述】:

我有一个 ParentComponent,它包含许多 ChildComponent。 ChildComponent 通过@Output() 公开一个EventEmitter。我用它来发出一些从 ChildComponent 包含的表单中收集的数据。

ParentComponent 可以将数据异步保存到我的后端服务器,但问题是,我需要以某种方式将保存操作的结果发送回 ChildComponent,以便它可以关闭表单或显示验证错误。

我正在考虑在我的子组件中创建某种主题并将其与实际数据一起发出,在父端我会得到发出的东西,使用数据发送到服务器,并使用 @ 987654322@ 将数据发布回子组件,但它看起来非常复杂和丑陋。

如果我要在子组件上使用 @Input 以便从 ParentComponent 接收更新,那么父组件必须知道哪个子组件发出了数据,这看起来不太好。

有什么好的解决方案来确保父子组件之间的异步双向通信?

【问题讨论】:

  • 你在使用响应式表单吗?

标签: angular


【解决方案1】:

我会使用主题但不在组件中,为了保持组件清洁,请使用具有 2 个主题的服务,一个孩子将用于向父级发送数据并订阅另一个,父级将使用该主题将数据发送回孩子们。 让我们创建双向服务

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";

@Injectable({providedIn: 'root'})
export class BidirectionalService {
    public p2cSubject = new Subject<{statusCode: number, msg: string}>(); //parent to 
child
    public c2pSubject = new Subject<{id: number, name: string}>(); //child to parent
}

这是孩子:

import { Component, OnInit } from '@angular/core';
import { BidirectionalService } from '../services/bidirectional.service';

@Component({
  selector: 'app-child1',
  templateUrl: './child1.component.html',
  styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {

  statusFromParent: number;

  constructor(private bs: BidirectionalService) { }

  ngOnInit(): void {
    this.bs.p2cSubject.subscribe((o) => {
      this.statusFromParent = o.statusCode;
    })
  }

  onSubmit1(input1: HTMLInputElement) {
    this.bs.c2pSubject.next({id: 100, name: input1.value});
  }

}

以及父组件:

import { Component, OnInit } from '@angular/core';
import { BidirectionalService } from './services/bidirectional.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = '';
  dataToBePosted: any;

  constructor(private bs: BidirectionalService) {}

  ngOnInit(): void {
    this.bs.c2pSubject.subscribe((o) => {
      this.dataToBePosted = o;
      setTimeout(() => {
        this.bs.p2cSubject.next({statusCode: 200, msg: 'success!'});
     }, 5000); //async
    })
  }
}

【讨论】:

  • 但是如果我这样做,不是所有的孩子都会收到相同的信息吗?
  • 哦,是的,但我们可以解决这个问题。您能否在每个发布请求中传递组件名称或一些 id,它会返回其响应,以便我们可以知道请求是为哪个孩子完成的。如果可能的话,我们可以做这样的事情 this.bs.p2cSubject.subscribe((o) =&gt; { if(o.additionalInfoFromResponse.childName === 'Child2') { //go ahead 。我可以看到它在这里变得有点骇人听闻,但如果它有效,对我来说似乎很好。请告诉我,我会相应地更新我的答案,如果对您没有帮助,请删除它。
【解决方案2】:

我要做的是使用Reactive Forms,这样父级将定义编码为一组字段的数据模型的整个结构(组和数组也可用)。然后使用普通的响应式表单 API,可以检测表单任何部分的变化并获得完整的表单值,例如。用于发送。

如果出现后端验证错误,父组件将简化setError 或表单的相关字段 - 子组件将必须负责显示/处理这些错误 - 所以这与您要采用的方法相同。

使用这种方法,您只需将表单组(甚至是表单的单个控件)传递给负责显示输入的子组件。不需要额外的事件,因为将通过反应式表单 API 通知父母有关表单中的数据更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 2021-03-02
    • 1970-01-01
    • 2011-11-09
    相关资源
    最近更新 更多