What is the best way to transfer a JSON Response from a service to a MatDialog Window?

I have a service that handles Http Requests to fetch User data by ID, and it's working fine.

On the other hand, I have a MatDialog where I need to display the JSON Response Data received from the service. The purpose of this process is to allow editing of User Data within the MatDialog, making changes, updating the data, and then triggering another Http Request to update the user before closing the dialog. This would involve using a submit button inside the MatDialog to send the edited User/Employee Data.

The first issue I'm currently facing is how to pass the data from the Response to the MatDialog?

login.service.ts:

getSingleUser(id) {
   let obsSingleUsersRequest = this.http.get(environment.urlSingleUsers + '/' + id, this.options)
   .map(res => {
       return res.json();
   }).catch( ( error: any) => Observable.throw(error.json().error || 'Server error') );
   return obsSingleUsersRequest;
}

The component responsible for executing and binding the button for the MatDilog edit-dialog.component.ts:

import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from "@angular/forms";
import { MatDialog, MatDialogRef } from '@angular/material';
import { EditUserComponent } from './edit-user/edit-user.component';
import { LoginService } from '../../_service/index';

@Component({
    selector: 'app-edit-dialog',
    templateUrl: './edit-dialog.component.html',
    styleUrls: ['./edit-dialog.component.css']
})
export class EditDialogComponent implements OnInit {
    dialogResult:string = '';

    constructor(public dialog:MatDialog, public loginService:LoginService) {}
    ngOnInit() {}
    openDialog() {
        let dialogRef = this.dialog.open(EditUserComponent, {
            width: '600px'
        });
        this.loginService.getSingleUser('59dc921ffedff606449abef5')
        .subscribe((res) => {
              console.log('User Data EDIT DIALOG: ' + JSON.stringify(res) );
          },
          (err) => {
              err;
              console.log('IN COMPONENT: ' + err);
          });
        dialogRef.afterClosed().subscribe(result => {
            console.log(`Dialog closed: ${result}`);
            this.dialogResult = result;
        })
    }
}

The Dialog Window component where I intend to display the JSON Data Response for editing purposes. edit-user.component.ts:

import { Component, OnInit, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { LoginService } from '../../../_service/index';


@Component({
    selector: 'app-edit-user',
    templateUrl: './edit-user.component.html',
    styleUrls: ['./edit-user.component.css']
})


export class EditUserComponent implements OnInit {

      constructor(
          public thisDialogRef: MatDialogRef<EditUserComponent>,
          @Inject(MAT_DIALOG_DATA) public data: string) { }

          ngOnInit() {}

      onCloseConfirm() {
          this.thisDialogRef.close('Confirm');
      }

      onCloseCancel() {
          this.thisDialogRef.close('Cancel');
      }

}

edit-dialog.component.html:

<mat-card-content>
   <mat-button-group>
       <i class="material-icons" (click)="openDialog()">create</i>
   </mat-button-group>
</mat-card-content>

Answer №1

  1. Retrieve JSON and display dialog

    openDialog() {
        this.loginService.getSingleUser('59dc921ffedff606449abef5')
            .map(data => {
                return this.dialog.open(EditUserComponent, { data: data }).afterClosed();
            }).subscribe(result => this.dialogResult = result);
    }
    

-- or --

  1. Show dialog immediately

     openDialog() {
        let request = this.loginService.getSingleUser('59dc921ffedff606449abef5');
        this.dialog.open(EditUserComponent, { data: request })
            .afterClosed()
            .subscribe(result => this.dialogResult = result);
    }
    

    then in dialog component:

    constructor(
        public thisDialogRef: MatDialogRef<EditUserComponent>,
        @Inject(MAT_DIALOG_DATA) public data: Observable<any>) { }
    
    ngOninit() {
        this.data.subscribe(data => /* do something */);
    }
    

-- even better --

  1. Include service in the dialog

     openDialog() {
        this.dialog.open(EditUserComponent, { data: '59dc921ffedff606449abef5' })
            .afterClosed()
            .subscribe(result => this.dialogResult = result);
    }
    

    then in dialog component:

    constructor(
        public thisDialogRef: MatDialogRef<EditUserComponent>,
        @Inject(MAT_DIALOG_DATA) public data: string,
        public loginService: LoginService) { }
    
    ngOninit() {
        this.loginService.getSingleUser(data)
            .subscribe(data => /* do something */);
    }
    

https://material.angular.io/components/dialog/overview#sharing-data-with-the-dialog-component-

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent repetition of errors during compiling in the ahead-of-time (AOT

I need assistance with optimizing my codebase in Angular 2 using angular-cli. When I run the command "ng build --prod", I encounter an error that is preventing the output of the dist folder. This error claims that there is a duplicate identifier in one of ...

The program encountered an error: Unable to access the 'toDate' property of an undefined value

Encountering an error in my Firebase project while running a Firebase function. The specific error message is: Cannot read property 'toDate' of undefined, related to converting admin.firestore.Timestamp to Date format. Any suggestions on how to ...

The error message TS2304 is indicating that the name 'Set' cannot be found in electron-builder

I am trying to utilize the AppUpdater feature in electron-builder for my Electron Application. Upon importing the updater in my main.ts file: import { autoUpdater } from "electron-updater" An error is triggered when running the application: node_module ...

Using a modulus operator in Angular 6 to conditionally show elements

Trying to achieve a specific layout for an object in an array using ng-For and ng-If. Here is the desired recovery code, and here's what I've attempted so far in my code snippet enter image description here: <div class="recovery-code" *ngFor= ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Angular 13 throws NG0301 error message, failing to display the problematic module

Can someone provide assistance? Recently, I upgraded my Angular project from version 11 to version 13: Angular: 13.2.4 ... animations, cdk, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package ...

Executing npm prepublish on a complete project

I am facing a situation with some unconventional "local" npm modules that are written in TypeScript and have interdependencies like this: A -> B, C B -> C C -> D When I run npm install, it is crucial for all TypeScript compilation to happen in t ...

What are the steps to customize the date pipe in Angular?

Encountered the InvalidPipeArgument issue with Safari for date/time format, but managed to resolve it by following the solution provided in this Stack Overflow thread. Currently using: <mat-cell *cdkCellDef="let payroll" fxFlex="20%"> {{payroll.tim ...

Do you need to use NextPage when developing NextJS applications with TypeScript?

When looking at the NextJS examples, particularly the one demonstrating how to incorporate TypeScript with NextJS, I noticed that they do not utilize the NextPage type. The specific file I am referring to can be found here: https://github.com/vercel/next- ...

Cypress error: Unable to access 'uid' property as it is undefined

Recently in my Cypress project with TypeScript support utilizing the Cucumber Preprocessor, an unexpected exception has started appearing: TypeError: Cannot read properties of undefined (reading 'uid') There are instances where changing to a di ...

Tips on connecting an Angular web application with Google authentication

Hello, I am exploring the Google Cloud Platform for the first time and need help with implementing Google sign-in on my Angular web application. I have searched for code solutions but haven't found anything useful yet. Can anyone recommend any documen ...

The 'push' property is not found within the 'Control' type

I am attempting to create an array that contains arrays within it. This array is intended for a dynamic form functionality, where the user can add a new section and push the array of control fields to the main array. Angular2 then generates this dynamical ...

Protractor fails to capture the presence of mat-dialog-container

My Protractor test for an Angular 5 application is functioning well, except when it has to handle a popup containing input fields. The HTML element representing the popup looks like this: <mat-dialog-container class="mat-dialog-container ng-tns-c26-5 n ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Error encountered when serving Angular due to node_modules/@types incompatibility (Build Issue)

When attempting to run 'ng build' after npm install, I encounter the following error message: ERROR in node_modules/@types/node/globals.d.ts(713,19): error TS2304: Cannot find name 'bigint'. node_modules/@types/node/ts3.6/base.d.ts(13,2 ...

What is the purpose of performing Dependency Injection within an Angular class constructor?

Recently, I've been diving into an article about Angular services and one question that has been on my mind is why the instance of the service is typically created in the class constructor? For example, let's say there is a DemoService class tha ...

Angular9: construction involves an additional compilation process

After updating my Angular8 project to Angular9, I noticed a new step in the build process which involves compiling to esm. This additional step has added approximately 1 minute to my build time. A snippet of what this step looks like: Compiling @angular/ ...

How can I programmatically assign an attribute to a FormControl?

Major question summarized: I am aiming to automatically set the readonly attribute to a dynamically generated FormControl (textbox) upon creation. Complete scenario: I have a Form with a dynamic component called FormRow, where elements (FormGroups) are ad ...

Issue: NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelper]:

While I am going through a tutorial on the abp framework, I encountered an error with the Author route that says "ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AuthorModule)[ScrollbarHelper -> ScrollbarHelper -> ScrollbarHelp ...

Tips for deleting markers from a TomTom map on a web application using Angular 5

I have integrated the TomTom map into my web application to display vehicles on the map. While I have successfully displayed the vehicles, I am now facing an issue with removing markers that have been added to the map. Please refer to the attached screens ...