从 angular material-dialog 获取数据

Get data from angular material-dialog

我需要你的帮助!我需要从“结果”到我的外部服务获取价值。但是它有一些麻烦,可能是因为异步工作。我如何从我的组件中获取它?我的 Angular 版本是 12。这是我的代码:

import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ModalComponent } from '../modal/modal.component';

@Injectable({
  providedIn: 'root'
})
export class ModalResultService {

  param!:string 

  constructor(
    public dialog: MatDialog
  ) { }

  dialogResult(){
    let dialogRef = this.dialog.open(ModalComponent)
    
    dialogRef.afterClosed().subscribe(
      result => {
        console.log(result);
      }
    )
  }
}

在我的外部服务中我想做这样的事情

update(note: Notation): Observable<Notation> {
    if (this.res.dialogResult())
      return this.http.patch<Notation(`${environment.fbDbUrl}/posts/${note.id}.json`, note);
    return of(this.dNotation)
  }

dNotation 是一些默认对象

我认为为了使组件可以用作对话框主体,我们还需要将其声明为 entryComponent。

您需要 return 一个 Observable 并一直使用异步代码。

dialogResult(): Observable<Boolean> {
    let dialogRef = this.dialog.open(ModalComponent)    
    return dialogRef.afterClosed();
}

在您的其他服务中:

update(note: Notation): Observable<Notation> {
    this.res.dialogResult().pipe(
      mergeMap(result => {
        if(result) { 
          return this.http.patch<Notation(`${environment.fbDbUrl}/posts/${note.id}.json`, note);
        } else {
          return of(this.dNotation);
        }
      }
    );
  }

注意:阅读关于 mergeMap 的 RxJs 文档,看看它是否适合您的用例。也许换个运营商更合适。