【问题标题】:Angular 6 - Child (Inner) Component emit an EventEmitter and wait to Parent Component return a respondAngular 6 - 子(内部)组件发出一个 EventEmitter 并等待父组件返回响应
【发布时间】:2019-06-12 16:59:11
【问题描述】:

我有这个组件作为父组件(facility.component),我在这个父组件中嵌入了一个子/内部组件(editableTable.component),就像这样

facility.component

  <editable-table 
  [dataList]="nursingUnitList" 
  (dataListUpdater)="updateNursingUnitList($event)">
  <editable-table>

facility.ts(调用服务并从 NursingUnit 表中获取所有数据)

 updateNursingUnitList(getUpdate: boolean) {
    if (getUpdate == true) {
      this.nursingUnitService.getAllUnits().subscribe(
        (data: nursingUnit[]) => {
          this.nursingUnitList = data;
        }
      )

在智利/内部组件中,我有这个,

editableTable.ts(通过单击刷新按钮,从 NursingUnit 表中获取最新/刷新的项目列表)

export class EditableTableComponent implements OnInit {

@Input() dataList: any[];
@Output() dataListUpdater = new EventEmitter<boolean>();

refresh() {

this.dataListUpdater.emit(true);

if (this.dataList.length != 0) {
// After getting updated/refreshed list do something here
// but I just got the dataList is null as the compiler not wait for emitter to get the updated/refreshed list from the parent component
    }

}

我的问题是如何在发出点等待以获取更新的列表,例如 angular 中的订阅服务或 C# 中的异步等待。

感谢您提供的任何帮助!

【问题讨论】:

    标签: angular async-await angular-services angular-event-emitter


    【解决方案1】:

    您可能想查看OnChanges 生命周期挂钩。

    export class EditableTableComponent implements OnInit, OnChanges {
    
      @Input() dataList: any[];
      @Output() dataListUpdater = new EventEmitter<boolean>();
    
      ngOnChanges(change: SimpleChanges) {
        if(change.dataList) {
          // do something
        }
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      在子组件(editableTable.ts)中,你可以实现一个 OnChanges 钩子,它看起来像这样:

      ngOnChanges(changes: SimpleChanges): void {
        const { dataList } = changes;
        if (dataList && dataList.previousValue !== dataList.currentValue) {
          'here call method which will handle dataList as you wish, because at this
           moment your dataList is updated from parent component. But don't call
           refresh() method because it will again emit Output from child component
           so you need to move code which handle dataList in a separate method.'
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-09
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2018-03-11
        • 2019-09-25
        • 1970-01-01
        • 2018-12-21
        相关资源
        最近更新 更多