Guide on accessing the afterClosed() method / observable in Angular from a Modal Wrapper Service

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
.

Answer №1

Your openWarningWindow function seems to be missing a return statement. Here's what it should look like:

openWarningWindow(warning) {

return this.zone.run(() => {
    // const dialogRef =
    return this.dialog.open(WarningComponent, {
      data: warning,
      panelClass: 'dialog--warning'
    });
});

}

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

How to Create a Dependency on Tabs for Selecting Items in an Angular 7 Materials Dropdown List

I am currently working with angular 7 in combination with angular materials. In my project, I have implemented a tab as well as a selection list. What I aim to achieve is that the items displayed in the selection list are dependent on the chosen tab in th ...

Do changes in Input fields reflect in the parent component?

I was under the impression that I could share data with child components using @Input() directive and communicate data back to the parent component with @Output() along with the appropriate emit. However, I recently discovered that modifications made to th ...

The async pipe value seems to be constantly null when dealing with router events

I am facing a straightforward problem while attempting to access an asynchronous property in my template - the returned value is consistently null. This is the method I am using: someAsyncProperty():Observable<string> { return this._router.event ...

Exploring nested objects and arrays with Plunker - extracting their values

I have retrieved two arrays, each containing nested objects, from API endpoints. One array (preview) consists solely of numbers. For example: [{ obj1:[1, 2], obj2:[3, 4] }] To obtain strings associated with IDs, I made another call to a different en ...

Displaying the initial element in an NgFor loop in Angular 2

Whenever I click on the "Add row" button, I dynamically generate a row of inputs and dropdowns. Upon clicking another button, the complete data is submitted and displayed in console.log as an array of objects, with each object representing a single row. C ...

Encountering the "Argument of type 'string' is not assignable to parameter of type 'never'" error when using Array.prototype.includes

The data type for keys is a combination of string[] | number[], which is derived from the ID type. The data type for id is simply ID. We want to check if the id exists within the array of keys. import React, { useState } from 'react'; type Distr ...

Managing animations with multiple components in Angular 2+

I am currently developing an Angular application that will utilize a series of Modals in a wizard-style setup. For this project, I am utilizing the Angular-cli tool. Below is the code snippet showing how I have set up my animations: animations:[ t ...

Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below: login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => { this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => { firebase.database().ref(&ap ...

Exploring SubjectBehavior within my UserService and Profile Component

Within my ShareService, I have the following code snippet: isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); <==== default value is false CheckUser = this.isLogin$.asObservable(); public isLogin (bool){ ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Angular2's ErrorHandler can cause code to malfunction when an error occurs

import { Injectable, ErrorHandler, Inject, Injector } from '@angular/core'; import { MessengerService } from '../services'; import { MessageTypeEnum } from '../../shared'; @Injectable() export class AppErrorHandler extends Er ...

Continuous Updates to innerHtml in Angular2

While working on a project, I encountered an issue that seems to be more about style than anything else. The endpoint I am calling is returning an SVG image instead of the expected jpeg or png format, and I need to display it on the page. To address this, ...

Discovering the Object with the Lowest Key Value in Typescript

Within my TypeScript code, I have defined a List as myList: Package[]. The structure of the Package model is outlined below - export class Package { ID: Number; Price: Number; } I am trying to retrieve a Package object with the lowest Price value using ...

Since updating from Angular 16 to 17, I am experiencing a TypeScript compilation issue specifically related to 'openui5'

Everything was running smoothly in Angular16. I had "@types/openui5" : "1.40.4" listed in my dev-dependencies. Here is how it's configured in the tsconfig.json: { "compilerOptions": { "downlevelIteration": ...

Angular component experiencing issues with implementing Bootstrap styles

I followed a tutorial to apply the bootstrap 5.3.0 style to my navigation bar, but the outcome looks different from what was shown in the tutorial. This is the HTML code for the navigation component: <nav class="navbar navbar-default"> & ...

Updating the Angular2 function in the main app component causes the current component to be reset

I developed an application that has the following structure: app.component.ts import { Component } from 'angular2/core'; import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router'; import { NgClass } from &apos ...

How can one interpret the act of "passing" an interface to an RxJS Store using angle brackets?

When working with NgRx and typescript, I often come across this syntax within class constructors: import { Store, select } from '@ngrx/store' class MyClass { constructor(private store: Store<AppState>) { this.count$ = store.pipe(sele ...

When attempting to initiate a new Angular project, the error below is being encountered

Seeking assistance with this error. I am attempting to create a new angular app using ng new app-name, but encountering the following issue. Being new to Angular, I'm unsure about the cause of this error. CREATE angular-app/e2e/src/app.e2e-spec.ts (3 ...

Tips for integrating assets such as icons into an Angular8 library

I've been attempting to integrate assets into an Angular 8 library. The library was initially created using ng generate library, and my objective is to incorporate SVG-format icons for use within the HTML component layouts. Up to this point, I have ...

Encountered a TypeError when using Angular 2 with ng-bootstrap and NgbTabset: Uncaught (in promise) error due to inability to read property 'templateRef'

I am attempting to use NgTabset but encountering an error that reads TypeError: Cannot read property 'templateRef' of undefined. Strangely, when I replace the ng-template with the template tag, everything works smoothly. Can anyone help me identi ...