首页 > 解决方案 > Angular(8)NgbModal DB插入和相同的数据将在父页面组件上刷新

问题描述

在我的 Angular (8) 中使用NgbModal。父页面,从 http 服务(java 和 mysql db)获取数据作为列表的组件之一。并且在模态提交时,它将在mysql db的同一张表中插入一条记录。现在在模态提交和关闭之后,如何用新数据刷新/更新组件列表数据。

Parent Component -> 打开模态组件

“selectedName”从数据库中获取并显示在父组件中。

 openEditProfilePage() {
    const modalRef = this.modalService.open(EditProfileComponent, { size: 'xl', scrollable: true });
    modalRef.componentInstance.selectedName = this.selectedName;

  }

子组件从父组件获取 selectedName 的值,并在表单中更新以附加一些字符串并保存。

 onSave(form: FormGroup) {

    if (form.valid) {

      this.nameService.editName(form.value).subscribe(
        res => {
          this.modalService.dismissAll();
        },
        error => {
          this.showError(error);
        }
      );
    }
  }

现在在子组件中,它会在dismissAll之后更新DB.so中的名称,模式/弹出窗口将被关闭,同时希望在父组件中显示更新的名称。

标签: angularbootstrap-modalng-bootstrappage-refresh

解决方案


通过查看文档,您似乎需要使用 NgbModalRef ( https://ng-bootstrap.github.io/#/components/modal/api#NgbModalRef ) 提供的结果承诺。当模式关闭时,承诺得到解决(或拒绝),因此您将能够在此时加载新列表。例如:在您的父页面 component.ts

constructor(private modalService: NgbModal) {}
open(content) {
    this.modalService.open(content).result.then((result) => {
        //call the method of refreshing your list here
    }, (reason) => {
        //called if the modal was dismissed for some reason
    });
  }

在您的模态组件html中

<div class="modal-footer">
    <!-- modal.close will cause the result promise to get resolved therefore executing the block of code that will refresh the items list -->
    <button type="button"(click)="onClose()">Save</button>
  </div>

在您的模态组件 ts 中,您必须在模态组件内注入服务才能使用您想要的方法

export class ModalComponent{
  constructor(private myHttpService: MyHttpService)\

  onClose(){
     this.myHttpService.methodToRefreshList()
     // close modal
  }

}


推荐阅读