我有一个包含多个ChildComponents的ParentComponent。ChildComponent通过@Output()
公开EventEmitter。我使用它来发出一些从ChildComponent包含的表单中收集的数据。
ParentComponent可以将数据异步保存到我的后端服务器,但问题是,我需要以某种方式将保存操作的结果发送回ChildComponent,以便它可以关闭表单或显示验证错误。
我正在考虑在我的子组件中创建某种类型的主题,并将其与实际数据一起发出,在父组件上,我将获得发出的内容,使用数据发送到服务器,并使用Subject
将数据发布回子组件,但这似乎非常令人费解和丑陋。
如果我使用子组件上的@Input
来接收来自ParentComponent的更新,那么父组件必须知道哪个子组件发出了数据,这似乎不太好。
有哪些很好的解决方案来确保父组件和子组件之间的异步双向通信?
发布于 2021-01-08 03:00:12
我要做的是使用Reactive Forms,这样parent就可以定义编码为字段集的整个数据模型结构(也可以使用组和数组)。然后使用普通的反应式表单API,可以检测表单的任何部分的变化,并获得完整的表单值,例如。用于发送。
在后端验证错误的情况下,父组件将简化表单的setError
或相关字段-子组件必须负责显示/处理这些错误-所以这正是您想要采取的方法。
使用这种方法,您只需将表单组(甚至表单的单个控件)传递给负责表示输入的子组件。不需要其他事件,因为家长将通过reactive forms API收到有关开箱即用表单中的数据更改的通知。
发布于 2021-01-08 03:07:53
我会使用Subject,但不会在组件中使用,为了保持组件的整洁,使用一个带有两个Subject的服务,一个子节点将用来向父节点发送数据,并将订阅另一个,父节点将用它将数据发送回子节点。让我们创建BidirectionalService
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
})
}
}
https://stackoverflow.com/questions/65617175
复制相似问题