在这种情况下,如何正确地将值从第二级子组件传递到父组件?

问题描述

我不太喜欢Angular和TypeScript(我来自Java),需要解决以下问题。我不知道我认为使用的解决方案是否正确,或者是否有更好的解决方案。

基本上,我有一个名为 order-manager.component 的组件,它是呈现此表的父组件:

enter image description here

此父组件包含代表单行的对象列表:

orders: any[];

并进入 ngOnInit(),使用服务检索列表。

您可以在上一个打印屏幕中看到,可以扩展表格的每一行,以显示/编辑特定对象的详细信息。

为此,我使用了一个名为 order-details 的子组件。所以基本上在我的父组件HTML中,我有这样的东西:

DETTAGLIO ORDINE

order-details 子组件本身具有2个子组件:一个用于查看模式,另一个用于编辑模式(在上一个屏幕截图)。

基本上,在我的 order-details 组件代码中,我简单地拥有:

<p-selectButton [options]="editOrderOption"
                [(ngModel)]="editOrderSelectedOption"
                (onChange)="editOrderOptionOnChange($event,orderDetail.id)"></p-selectButton>


<div *ngIf="editOrderSelectedOption=='view';then view_content else edit_content">here is ignored</div>

<ng-template #view_content>
  <app-view-order [orderDetail]="orderDetail"></app-view-order>
</ng-template>

<ng-template #edit_content>
  <app-update-order [orderDetail]="orderDetail"></app-update-order>
</ng-template>

基本上,用户通过选择按钮选择视图或编辑模式,然后在页面中呈现一个子组件。

在特定情况下,我们使用此更新顺序组件进入编辑模式

如上图所示,此更新顺序组件允许用户编辑表单,最后包含删除按钮。单击此按钮,我想从我的表中删除代表该顺序(表的这一行)的对象。

这是我的问题。代表表行的对象列表在第一个 order-manager.component 父组件中定义,而按钮在第二个 update-order 子组件中定义,是层次结构:

order-manager component
          |
          |
          |---------> order-details component
                                |
                                |
                                |----------------> update-order component

                 

为了解决这个问题,我想我可以做这样的事情:

  1. 用户单击定义在更新顺序子组件中的删除按钮。这可以通过一种方法来处理,该方法发出一个包含当前行ID(它是object字段的唯一值)的事件。

  2. 进入 order-manager 父组件,我监听此事件。收到事件后,该事件将从代表我的表的行列表的 orders 列表中删除

您认为实现此任务是一个不错的解决方案吗?还是我错过了一些东西,还有更好的解决方案?

解决方法

发送值即可。

一个更简单的解决方案是创建一个可以跟踪用户操作的服务。 创建一个服务说OrderChangeService并将其注入order-manager componentupdate-order component

export class OrderChangeService {
  deleteIdSubject$ = new Subject<number>(); // import { Subject } from rxjs
  deleteIdAction$ = deleteIdSubject$.asObservable()
}

现在update-order component中,当用户单击以删除特定订单时,您可以在主题上调用next()函数

  deleteOrder(id: number) {
    deleteIdSubject$.next(id);
  }

现在,您可以在订单管理器组件的deleteIdAction$函数中订阅ngOnInit()

deleteIdAction$ = this.orderChangeService.deleteIdAction$ // make sure you inject service in the constructor
  ngOnInit() {
    this.deleteIdAction$.subscribe({
      next: (id) => {
        // Do Delete action for item with id
      }
    })
  }

基本思想是,可以使用服务将信息从一个组件传递到另一个组件。随着嵌套组件深度的增加,发射值可能会出现问题

最佳方法实际上是使用NgRx进行状态管理。可能有点难以使用,但会产生更好的结果。您可以看看official documentation of NgRx

,

相反,您可以创建一个数据服务来更新和通过它获取数据

import { Injectable } from '@angular/core';
import { Subject,Observable } from 'rxjs';
@Injectable()
export class MessageService {
  private siblingMsg = new Subject<string>();
  constructor() { }
  /*
   * @return {Observable<string>} : siblingMsg
   */
  public getMessage(): Observable<string> {
    return this.siblingMsg.asObservable();
  }
  /*
   * @param {string} message : siblingMsg
   */
  public updateMessage(message: string): void {
    this.siblingMsg.next(message);
  }
}

,然后从组件中,可以使用subscription设置值。

import { Component,OnInit,OnDestroy } from '@angular/core';
import { MessageService } from './message.service';
...
export class AppComponent implements OnInit{
  public messageForSibling: string;
  public subscription: Subscription;
  constructor(
    private msgservice: MessageService // inject service
  ) {}

  public ngOnDestroy(): void {
    this.subscription.unsubscribe(); // onDestroy cancels the subscribe request
  }

  public ngOnInit(): void {
    // set subscribe to message service
    this.subscription = this.messageService.getMessage().subscribe(msg => this.messageForSibling = msg);
  }
}
,

首先,您应该在子组件中创建一个输出属性。

  @Output() 
  updated = new EventEmitter<boolean>();
  
  saveButtonClicked() {
    
    //do update
    
    this.updated.emit(true); //update success
    
  }

在您的html中定义它:

<ng-template #edit_content>
  <app-update-order [orderDetail]="orderDetail" (updated)="orderUpdated($event)"></app-update-order>
</ng-template>

现在,您可以在父组件中监听更新事件了。

orderUpdated(updated:boolean){
    if(updated){
    
    }
}

您可以找到有关组件交互here

的更多信息