3

I'm trying to implement custom confirm dialog functionality which is planned to be available app-wide - across all components.

For that I use Angular Material.

The modal is a separate component which I resolve in another component in the following way:

const dialogRef = this.confirmDialog.open(ConfirmDialogComponent, ... });

The problem I face - with this approach I have to duplicate the code in every component. DRY principle is violated.

For more details:

...
export class SearchComponent extends AppComponentBase {...

    constructor(public confirmDialog: MatDialog, ...) { super(injector); }

    confirm(title: string, message: string) {
        var promise = new Promise((resolve, reject) => {

            const dialogRef = this.confirmDialog.open(ConfirmDialogComponent, {
                width: '250px',
                data: { title: title, message: message }
            });

            dialogRef.afterClosed().subscribe(result => {
                if (result) {
                    resolve();
                } else {
                    reject();
                }
            });
        });
        return promise;
    }

Obviously I could move the shared code to a base component - AppComponentBase. Although there will still be bits of duplicated code - e.g. constructor-related code.

But, is there a better / cleaner approach in terms of software design to refactor what I have?

Thanks.

Alex Herman
  • 2,708
  • 4
  • 32
  • 53
  • 1
    Why don't put in your app.component? Is like when we want to have a navigation sistem common to all the application – Eliseo Jul 05 '18 at 22:21

1 Answers1

5

For a working example StackBlitz

Put this in a /shared or /services folder at the root level.

The service:

import { Observable } from 'rxjs';
import { MessagesComponent } from './messages.component';
import { MatDialogRef, MatDialog } from '@angular/material';
import { Injectable } from '@angular/core';

@Injectable()
export class MessagesService {

  dialogRef: MatDialogRef<MessagesComponent>;

  constructor(private dialog: MatDialog) { }

  public openDialog(title: string, message: string): Observable<any> {
    this.dialogRef = this.dialog.open(MessagesComponent);
    this.dialogRef.componentInstance.title = title;
    this.dialogRef.componentInstance.message = message;

    return this.dialogRef.afterClosed();

    // Nothing can live after afterClosed.
  }
}

The component.ts

import { Component, OnInit } from '@angular/core';

import { MatDialogRef } from '@angular/material';


@Component({
  selector: 'app-messages',
  templateUrl: './messages.component.html'
})
export class MessagesComponent implements OnInit {

  public title: string;
  public message: string;


  constructor(
    private dialogRef: MatDialogRef<MessagesComponent>,
  ) { }


  private closeWithTimer() {
    setTimeout (() => {
      this.dialogRef.close();
    }, 2000);
  }


  ngOnInit() {
    this.closeWithTimer();
  }
}

The html:

<h1 mat-dialog-title>{{title}}!</h1>
<div mat-dialog-content>{{message}}</div>

Calling from some component in your universe:

constructor(
    private httpService: HttpService,
    public dialogRef: MatDialogRef<AddMemberComponent>,  // Used by the html component.
    private messagesService: MessagesService,
    public formErrorsService: FormErrorsService
  ) { }

this.httpService.addRecord(this.membersUrl, enteredData)
      .subscribe(
        res => {
          this.success();
        },
        (err: HttpErrorResponse) => {
          console.log(err.error);
          console.log(err.message);
          this.handleError(err);
        }
      );

At the bottom of that component's ts:

  private success() {
    this.messagesService.openDialog('Success', 'Database updated as you wished!');
  }

  private handleError(error) {
    this.messagesService.openDialog('Error addm1', 'Please check your Internet connection.');
  }
Preston
  • 3,260
  • 4
  • 37
  • 51