Can one invoke ConfirmationService from a different Service?

How can I declare an application-wide PrimeNG dialog and display it by calling ConfirmationService.confirm() from another service? Below is the HTML code in app.component.html:

<p-confirmDialog
[key]="mainDialog"
class="styleDialog"
[baseZIndex]="10000"
> </p-confirmDialog>

Next, I create a service called dialogue.service.ts:

@Injectable({providedIn: 'root', })    

  export class FooService{

  constructor(
  
   private confirmationService: ConfirmationService,

    ) {}

  doSomeStuff() {

  this.confirmationService.confirm({
  key:'mainDialog',
  message: 'some message',
  header: 'Warning',
  icon: 'pi pi-exclamation-triangle',
  acceptLabel: 'ok',
  rejectVisible: false,
  accept: () => {},
  });
}
 } 

--> My implementation does not seem to be working. Am I missing something? Any help would be greatly appreciated.

Thank you for your response.

Answer №1

Alright, so the initial issue here is that you're utilizing key as a directive (like [key]). This signifies that within it, you have to mention a property declared in the component. Instead, you can directly use a string, so modify your HTML like this:

<p-confirmDialog key="mainDialog" class="styleDialog" [baseZIndex]="10000">
    Content
</p-confirmDialog>

Next, in your app.module.ts, make sure to include the ConfirmationService as a provider:

@NgModule({
  declarations: [
    AppComponent,
...
  ],
  imports: [
...
    ConfirmDialogModule
  ],
  providers: [ConfirmationService],
  bootstrap: [AppComponent]
})

Moreover, I observed an error in your FooService. It seems to be a result of a copy/paste from StackOverflow, but nonetheless, here's how you should correct it:

import {Injectable} from '@angular/core';
import {ConfirmationService} from 'primeng/api';

@Injectable({
  providedIn: 'root'
})
export class FooService {

  constructor(private confirmationService: ConfirmationService) {
  }

  confirm(): void {
    this.confirmationService.confirm({
      key: 'mainDialog',
      message: 'some message',
      header: 'Warning',
      icon: 'pi pi-exclamation-triangle',
      acceptLabel: 'ok',
      rejectVisible: false,
      accept: () => {
        console.log('accept');
      },
    });
  }
}

Remember to declare and invoke your FooService.confirm method whenever you require it. For example, if you need it in the app.component.ts, your implementation would look something like this:

import {Component, OnInit} from '@angular/core';
import {FooService} from './foo.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private fooService: FooService) {
  }

  ngOnInit(): void {
    this.fooService.confirm();
  }
}

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

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Utilizing TypeScript path aliases in a Create React App project with TypeScript and ESLint: A step-by-step guide

I utilized a template project found at https://github.com/kristijorgji/cra-ts-storybook-styled-components and made some enhancements. package.json has been updated as follows: { "name": "test", "version": "0.1.0" ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

Optimal Strategies for Handling CORS in Angular 2+ and Node/Express Servers

Currently, I am in the process of implementing user authentication with Express/Node and testing cookies from an Angular frontend. Upon logging in, the cookies are properly displayed in the network tab but not in the application tab. I understand that usi ...

Completion of TypeScript code is not working as expected, the variable that is dependent upon is not

Looking for assistance with creating code completion in TypeScript. Variable.Append1 Variable.Append2 Variable.Append3 I have defined the following class: class Variable { Append1(name: string){ if (name == undefined) ...

Passing data from the <ion-content> element to the <ion-footer> element within a single HTML file using Ionic 2

In my Ionic 2 html page, I have a setup where ion-slide elements are generated using *ngFor. I am seeking a way to transfer the data from ngFor to the footer section within the same page. <ion-content> <ion-slides> <ion-slide *n ...

Guide to generating a dropdown menu and linking it with data received from a server

I am completely new to Angular and recently received a project involving it. My task is to create a nested dropdown list for Json data retrieved from a server using Rest Api calls. The data contains a Level attribute that indicates the hierarchy level of ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

When using the RxJs Pipe with MAP in Angular and Ionic, it may not return a value in windows, but it works perfectly in Mac when used with HttpClient

I'm currently using RxJs Pipe with Map for a network request in my Angular/Ionic project. Interestingly, while I do receive a successful response in the network log, the MAP function fails to return any value. Notable Observations Strangely, this fu ...

What is the best way to expand upon the declaration file of another module?

I have encountered a problem with declaration files in my AdonisJS project. The IoC container in Adonis utilizes ES6 import loader hooks to resolve dependencies. For instance, when importing the User model, it would appear as follows: import User from ...

Change the color of active buttons on dynamically generated buttons

My current challenge involves getting a button to stay active when pressed, especially when dealing with dynamically created buttons. Here is my current setup: <Grid container sx={{ padding: "10px" }}> {Object.values(CATEGORIES).map((c) => { ...

Creating a Typescript interface for a sophisticated response fetched from a REST API

I'm currently struggling with how to manage the response from VSTS API in typescript. Is there a way to handle this interface effectively? export interface Fields { 'System.AreaPath': any; 'System.TeamProject': string; 'Sys ...

I prefer to have static modules generated on the home page rather than dynamic ones

As a newcomer to Angular, I am facing an issue with dynamic modules in my project. Currently, all modules are being generated when I run the project, but I only want to generate the login page module. Below is a screenshot and the code from the app.routing ...

best practices for choosing items from a dropdown menu using Angular

I have a dropdown list displaying existing tags/chips created by users in the past. However, I'm having an issue where when I select a tag from the dropdown list, it doesn't show up in my input field (similar to the Chart tag currently). I am abl ...

What is the process for choosing nested colors from a theme in Material UI?

I have a question regarding how to select a nested style from my theme when creating a Button. Below is the snippet of code that illustrates my dilemma: const buttonStyle: SxProps<Theme> = { '&:hover': { backgroundColor: 'bac ...

Tips for elegantly merging two Observables within an RXJS pipeline

I am working on developing a log viewer using Angular. Upon user entry, I aim to load historical logs and also begin monitoring for new logs. Users have the ability to filter logs using a simple form that emits a query object. Each time the query changes, ...

The presence of a constructor in a component disrupts the connection between React and Redux in

I am facing an issue with the connect function from 'react-redux' in my Typescript class example. The error occurs at the last line and I'm struggling to understand why it's happening. The constructor is necessary for other parts of the ...

Getting the length of child elements in Angular using ngFor loop

Can anyone help me figure out how to check the length of a child element in my Angular *ngFor loop? I am fetching data from a real-time firebase database. What am I doing wrong? Here is the code snippet I am using: <div *ngFor="let event of events"> ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...