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

tips for utilizing a variable for inferring an object in typescript

In my current code, I have the following working implementation: type ParamType = { a: string, b: string } | { c: string } if ('a' in params) { doSomethingA(params) } else { doSomethingC(params) } The functions doSomethingA and doSomething ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

Progressive series of observable conditions

The issue at hand: I am faced with the task of checking multiple conditions, some of which lead to the same outcome. Here is the current flow: First, I check if a form is saved locally If it is saved locally, I display text 1 to the user If not saved l ...

What is the best way to pass a URL as a prop in Next.js without encountering the issue of it being undefined

Within my file (handlers.ts), I have a function designed to post data to a dynamic API route while utilizing the app router. This function requires values and a URL for fetching. However, when I pass the URL as a prop like this: http://localhost:3000/unde ...

Implement a conditional statement in Angular 5 to dynamically control the layout of Bootstrap columns in

I am facing an issue in my Angular 5 project where I need to display certain columns based on specific conditions. Recently, I updated Bootstrap to version 4 and now I am encountering a problem with conditional templates. Some columns with the "ng-star-in ...

Assigning a value and specifying the selected attribute for an options tag

Trying to understand the challenge of setting both a value and a selected attribute on an options tag. Each one works independently, but not together. For example: <select> <option *ngFor="let item of items" selected [ngValue]="item"> ...

insert a gap between two elements in the identical line

Is there a way to create spacing between two text fields in the same row? I have tried using margins, paddings, and display flex in the css file but haven't been successful. import "./styles.css"; import TextField from "@material-ui/cor ...

The node controller function is receiving an undefined object value

Recently, I built a contact form using Angular 7 and connected it with Nodemailer to send the form details to a specified email upon submission. While the frontend view functions properly and sends values correctly, I encountered an issue on the backend wh ...

TypeScript Angular Forms: Implementing correct typing for dynamic form fields

I have a formgroup that looks like this: this.formBuilder.group<{ id: number; nameDe?: FormControl<string>; nameFr?: FormControl<string>; nameIt?: FormControl<string>; }>({ id: value?.id || null }); The main foc ...

Tslint is notifying that JSX elements without any children must be self-closing to prevent errors [Error]

Recently, I encountered an issue while trying to build my solution using the command npm run build. The error message displayed was: JSX elements with no children must be self-closing. I came across a similar problem on Stack Overflow but unfortunately ...

What is the best way to establish communication between a child and grandfather component in React?

I am currently developing an application using Angular 2. In my specific situation, I have three main components: SearchComponent: This component is responsible for calling a web service and injecting the results into SearchResultComponent. SearchResultC ...

What is the best way to incorporate a 'category filter' in Angular2?

Unique Scenario In my Angular2 application, I have implemented code in a component's view parent.component.html that iterates through an array of items and generates a new component for each item: <div class="list-items"> <!-- The colored ...

Learn how to send error logs from an Angular frontend to the backend using a custom API or any other method to store them in the Serilog table in MSSQL

Is there a way to log errors from an Angular frontend to a backend using a custom API or any other method that can send the data to Serilog's SQL sink table in MSSQL? My application utilizes multiple APIs from various third-party resources, and I need ...

Utilizing "regression-js" within an Angular 2 project: A comprehensive guide

I have integrated the Regression npm module https://www.npmjs.com/package/regression into my Angular 2 application to utilize the Linear Regression functionality. I installed the package using "npm install regression". However, I encountered errors while a ...

Filtering server-side components in Next.js to create a customized list

Having been accustomed to the previous architecture of Next.js, I embarked on a new project where I am exploring the use of server and client components in the latest architecture. Specifically, I have a page dedicated to displaying race results in a tabl ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. https://i.sstatic.net/CZTO2.png The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it s ...

Angular does not update the progress bar

Imagine having a component html with your own customized round progress bar <round-progress #progress [current]="current" </round-progress> The "Current" value represents the percentage. In my TypeScript component, I have written: ...

Angular 2: Change Boolean value depending on a condition

I find myself facing a challenge with a search-bar feature. My goal is to display all the filtered names when the input value reaches a length of 2 or more characters. After successfully extracting the value.length from the input field, I encountered a ro ...

The marker is not updating in real-time with the actual latitude and longitude on the Google Maps angular

I have been attempting to update the marker in my Angular Google Map in real-time, but unfortunately it is not working as expected. It only displays the initial static data and then fails to update. Despite conducting a thorough search on Google, I have be ...

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...