Get data from angular material-dialog

Issue

I need your help! I need to get a value from ‘result’to my external service. But there are some troubles with it, maybe because of async working. How can I get it from my component? My Angular version is 12. This is my code:

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);
      }
    )
  }
}

In my external service I want to do something like this

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 is some default object

Solution

You need to return an Observable and use async code all the way.

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

And in your other service:

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);
        }
      }
    );
  }

Note: read RxJs documentation about mergeMap to see if it fits your use case. Maybe another operator is more appropriate.

Answered By – Gaël J

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.