Currently, I am in the process of teaching myself coding and Angular by developing a personal app. Within my app, I have created a wrapper service for the Angular Material ModalDialog. It's a mix of Angular and AngularJS that I've been working on for quite some time now.
The structure of my wrapper service is as follows:
export class ModalDialogWrapperService {
constructor(private dialog: MatDialog, private zone: NgZone) {
}
openWarningWindow(warning) {
this.zone.run(() => {
const dialogRef = this.dialog.open(WarningComponent, {
data: warning,
panelClass: 'dialog--warning'
});
dialogRef.afterClosed().subscribe(() => {
console.log('I need access to this');
});
});
}
Using this service, I can easily trigger the Modal from an Angular Component by importing my service and invoking the method like so. Here is an example of a Component Method utilizing the service:
// component code
public raiseWarning(warning: any): void {
this.modalDialogWrapperService.openWarningWindow({
type: warning.type,
id: warning.id,
tags: warning.tags
});
}
However, I am facing a challenge when trying to access the information returned when the Dialog is closed. Even though I can capture it within my service using console.log
, I struggle to access it in a Component. Should I modify the component code as follows?
// component code
public raiseWarning(warning: any): void {
const dialogRef = this.modalDialogWrapperService.openWarningWindow({
type: warning.type,
id: warning.id,
tags: warning.tags
});
dialogRef.afterClosed().subscribe(() => {
console.log('I am in the component');
});
}
My attempt at modifying the Component Code with the amended return
statement in the service didn't yield success. I encountered the error
TypeError: Cannot read property 'afterClosed' of undefined
. Therefore, my question remains: how do I expose the afterClosed().subscribe
from my wrapper service to a component? Any guidance would be highly appreciated. Is there a necessity to return
the dialogRef
from the service like so?
openWarningWindow(warning) {
this.zone.run(() => {
// const dialogRef =
return this.dialog.open(WarningComponent, {
data: warning,
panelClass: 'dialog--warning'
});
});
}
I attempted this approach alongside the updated Component Code, but unfortunately, it did not resolve the issue. The same error persists -
TypeError: Cannot read property 'afterClosed' of undefined
.