angular 如何在父组件中关闭对话框后获取服务返回的对话框的响应数据

How to get response data of dialog box returned by a service after dialog box is closed inside parent component in angular

我创建了将数据传递到对话框的接口,作为可重用的组件。

公司新闻-interfaces.ts

export interface ConfirmDialogData {
    title: string;
    description: string;
    imageSrc: string;
    showText: boolean;
    modalFormData: any;
}

我在父组件中调用以上接口打开对话框

create-news.component.ts -- 父组件

  openDialog(){
    this.companyNewsDialogServiceService.confirmDialog({
      title: 'CardImage',
      description: 'Card Image Description',
      imageSrc: "",
      modalFormData: "",
      showText: false
    });
  }

    openPersonDialog(){
    this.companyNewsDialogServiceService.confirmDialog({
      title: 'Responsible Person Image',
      description: 'Responsible Person Image Description',
      imageSrc: "",
      modalFormData: "",
      showText: true
    }); 
  }

  openAssetDialog(){
    this.companyNewsDialogServiceService.confirmDialog({
      title: 'Assets Image',
      description: 'Assets Image Description',
      imageSrc: "",
      modalFormData: "",
      showText: true
    }); 
  }

以上函数调用company-news-dialog-service.service.ts中定义的confirmDialog函数来传递create-news.component.ts中定义的接口数据给各自的dialogbox

下面是公司-新闻-对话-service.service.ts文件

公司新闻对话-service.service.ts

@Injectable({
  providedIn: 'root'
})
export class CompanyNewsDialogServiceService {
  recivedFormData: any;
  constructor(private dialog : MatDialog) { }
  confirmDialog(data: ConfirmDialogData) {
    debugger
    return this.dialog.open(UploadFileDialogComponent, {data}).afterClosed().subscribe(res =>{
      this.recivedFormData = res;
      console.log('formdata',this.recivedFormData)
    });
  }
}

在上面的代码中,我在对话框关闭后从我的对话框组件 (upload-file.component) 获取响应数据。

下面是dialog-boxt(upload-file.component)组件代码

upload-file.component.ts -- 子组件

import { Component, ElementRef, EventEmitter, Inject, OnInit, Output, VERSION, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FileUploadService } from 'projects/shared-lib/src/lib/file-upload.service';
import { ConfirmDialogData } from 'projects/shared-lib/src/lib/shared-interfaces/companynews-interfaces';
// import { ConfirmDialogData } from 'projects/shared-lib/src/lib/shared-interfaces/pagination-interfaces';

@Component({
  selector: 'app-upload-file-dialog',
  templateUrl: './upload-file-dialog.component.html',
  styleUrls: ['./upload-file-dialog.component.scss']
})

export class UploadFileDialogComponent implements OnInit {
  fileType: boolean;
  linkType: boolean;
  file: any;
  fileUploadPending = true;
  message: string;
  modalFormData: any;
  imagePath: any;
  dataimage: any;
  show: boolean = true;
  uploadedImagePath: string;
  allLanguages: string[] = ['en', 'de', 'fr', 'ar', 'zh'];
  selectedForm: FormGroup;
  selectedLanguage: string = 'en';
  @ViewChild('fileInput') fileInput: ElementRef;
  fileAttr = 'Choose File';
  constructor(private matdialogref: MatDialogRef<UploadFileDialogComponent>, private fb: FormBuilder, @Inject(MAT_DIALOG_DATA) public data: ConfirmDialogData, private fileUploadService: FileUploadService) {
   this.setForm()
  }

  ngOnInit(): void {
    console.log(this.matdialogref)
  }
  setForm(){
    this.selectedForm = this.fb.group({
      text: [''],
      link: [''],
      language: [this.selectedLanguage],
      filepath: [this.uploadedImagePath]
    })
    console.log("57", this.selectedForm)
  }
  get getLink(){
    return this.selectedForm.get('link')?.value == ""
  }
  onClickFile() {
    this.fileType = true;
    this.linkType = false
  }
  onClickLink() {
    this.fileType = false;
    this.linkType = true
  }
  onClose() {
    this.matdialogref.close()
  }
  onItemChange(value : any){
    console.log(value);
    let val = value.target.id;
    console.log(" Value is : ", val );
    if(val === "en"){  
    }
  }
  uploadFile() {
    debugger
    this.fileUploadService.UploadFile(this.file).subscribe((res: any) =>{
      console.log("83",res)
      console.log("83",res.data)
      console.log("83",res.data.uploadedFilePath)
      this.uploadedImagePath = res.data.uplodedFilePath
      this.setForm()
      this.modalFormData = this.selectedForm.value
      console.log("modal",this.modalFormData)
      this.matdialogref.close({data: this.modalFormData})
    })
  }
  removeOnClick() {
    this.show = !this.show;
    this.fileAttr = ''
  }
  uploadFileEvt(imgFile: any) {
    this.file = imgFile.target.files[0];
    console.log(this.file)
    if (imgFile.target.files && imgFile.target.files[0]) {
      this.fileAttr = '';
      Array.from(imgFile.target.files).forEach((file: any) => {
        this.fileAttr += file.name + ' - ';
      });

      // HTML5 FileReader API
      let reader = new FileReader();
      reader.onload = (e: any) => {
        let image = new Image();
        image.src = e.target.result;
        const [file] = imgFile.target.files;
        image.onload = rs => {
          let imgBase64Path = e.target.result;
          // console.log(imgBase64Path);
          this.data.imageSrc = imgBase64Path;
          console.log(this.data.imageSrc)
        };
      };
      reader.readAsDataURL(imgFile.target.files[0]);

      // Reset if duplicate image uploaded again
      this.fileInput.nativeElement.value = "";
      this.show = false
    } else {
      this.fileAttr = 'Choose File';
    }
  }
  getAssetType(){

  }
  selectLanguage(language : any){
    this.selectedLanguage = language;
    console.log(this.selectedLanguage)
  }
}

在 uploadFile() 函数中的上述代码中,我传递了从输入字段收集的表单值以及上传文件端点返回的文件路径 - (text, link, language, filepath) 作为 modalFormData对话框关闭后。

我在以下时间收到此数据 company-news-dialog-service.service.ts 服务文件作为响应,如下面的屏幕截图所示。

我需要在create-news.component.ts.

中company-news-dialog-service.service.ts返回的响应数据

由于您的 CompanyNewsDialogServiceService 已经订阅了正在关闭的对话框,您需要在该服务上创建一个新的“可订阅”属性,以便调用 confirmDialog 方法可以在数据可用时获取该数据

export class CompanyNewsDialogService {
  recivedFormData: any;
  
  dataReceived: Subject = new Subject()  ; // create a new Subject
  
  constructor(private dialog : MatDialog) { }
  
  confirmDialog(data: ConfirmDialogData) {
    debugger
    return this.dialog.open(UploadFileDialogComponent, {data}).afterClosed().subscribe(res =>{
      this.recivedFormData = res;
      dataReceived.next(res) ; //to notifiy the subscribed parent/component 
    });
  }
}

然后,当您打开对话框时,您就订阅了该 dataReceived 主题。

openDialog(){
    //subscribe to the subject of the service 
    this.companyNewsDialogService.dataReceived.subscribe(data => console.log(data))

    this.companyNewsDialogService.confirmDialog({
      title: 'CardImage',
      description: 'Card Image Description',
      imageSrc: "",
      modalFormData: "",
      showText: false
    });
}

同时考虑将您的服务从 CompanyNewsDialogServiceService 重命名为 CompanyNewsDialogService

了解更多详情 https://www.tektutorialshub.com/angular/subjects-in-angular/