将数据从一个组件传输到另一个组件 angular

transfer data from one component to another angular

我有 组件 A 触发 MatDialog

  openDialog(): void {
   // console.log('The dialog was opened');

    const dialogRef = this.dialog.open(PicuploadComponent, {
      width: '1000px',
      //data: {name: this.name, animal: this.animal}
    });

    dialogRef.afterClosed().subscribe(result => {
// I want to get data from upload response here! **res**
    });
  }

此组件触发 PicuploadComponent,我在其中上传图像并接收包含一些数据的响应

onUpload() {
  const fd = new FormData(); 
  fd.append('image', this.selectedFile);
  this.service.uploadImage(fd).subscribe(
    (res:any)=>
    {
      console.log(res) ;
      this.dialogRef.close();
    },    
  );
}

PicuploadComponent 中试试:

this.dialogRef.close(res);

访问 组件 A 中的资源:

dialogRef.afterClosed().subscribe(result => {
  console.log(result)
});

当您关闭对话框时。

this.dialogRef.close({data:'data'});

当对话框完全关闭时。

let dialogRef = this.dialog.open(PicuploadComponent, dialogConfig).afterClosed()
  .subscribe(response => {
    console.log(response);
  });

如果您有任何疑问,请告诉我。谢谢

您应该将 uploadImage 调用的结果传递给 this.dialogRef.close() 方法。请参阅其文档中的示例,https://material.angular.io/components/dialog/overview