Creating an alert service in Angular 2

Recently, I encountered an alert within my contractorService.ts:

public showAlertPopup(title: string, message: string, cancelBtnText: string, confirmBtnText: string, onConfirm: any, onCancel: any): void {
    console.log("onConfirm function: ", onConfirm);
    const alertPopup = this.alertCtrl.create({
      title: title,
      message: message,
      buttons: [
        {
          text: cancelBtnText,
          handler: () => {
            onCancel();
          }
        },
        {
          text: confirmBtnText,
          handler: () => {
            onConfirm();
          }
        }
      ]
    });
    alertPopup.present();
  }

I realized that I might need to invoke this service from multiple locations. How can I pass the confirm and cancel functions along with parameters?

requestComponent.ts:

public test(): void {
    console.log('testing');
}

Another method inside requestComponent.ts:

someOtherFunc(): void {
    this.service.showAlertPopup('title', 'message', 'Cancel', 'OK', this.test, null);
}

The above implementation works fine. However, when I attempted:

public test(param: any): void {
    console.log('testing: ', param); // the parameter is undefined.
}

someOtherFunc(): void {
    this.service.showAlertPopup('title', 'message', 'Cancel', 'OK', this.test.bind('test parameter'), null);
}

I encountered the issue of getting 'testing: undefined' in the output.

Answer №1

Another helpful option to consider is:

this.service.showConfirm('title', 'message', 'Cancel', 'OK, () => this.test('test param'), null);

I find this method to be the most sophisticated approach for handling tasks like these.

Answer №2

Make sure to provide the arguments in the following way :

this.service.showConfirm('title', 'message', 'Cancel', 'OK', this.test.bind(this, 'Yes'), null);

Take note of the this.test.bind(this, 'Yes') parameter. It's important to pass the current context (this) to the function being called, since your test method is within the component.

Answer №3

this.contractorService.showConfirm("Proceed?", "Charges will be applied to your credit card", "Back", "Continue", this.test.bind(this.test, 'a'), this.cancel);

It seems like passing a function with arguments is necessary in this case. The code snippet above is functional.

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

Handling type errors with React Typescript MuiAccordion OnChange event handler

I'm a beginner in typescript and seeking advice on defining the type for an event handler. I have a component that utilizes material ui Accordion and triggers the handler from a container. Therefore, I need to specify the type of handleChange in my co ...

Error in CORS header due to absence of 'audience' token in Ionic 4 - Lambda configuration

I have an app built with Ionic framework running on my computer (localhost) that is accessing routes from my Lambda application. However, when I attempt to access a route, I encounter the following error: Cross-Origin Request Blocked: The Same Origin Po ...

Modify the contents of an input box according to the values entered in other input boxes

I have a specific requirement that I am trying to illustrate with an example. In this example, there are three input fields. Two of the input fields are independent, while the third input field is dependent on the values entered in the other two fields. ...

I am looking to load the component within the detailed view

I used Bootstrap to create a template with a sidebar and top navigation bar. However, when I click the button in the navbar, it loads the component below the page. As a beginner in Angular, I am unable to figure out what the problem is. Thank you for your ...

Exploring the Viability of Utilizing TypeScript and ES6 Modules for a Compact Library Package

Currently, our team is in the process of developing a custom JavaScript library for integration with one of our flagship products. The development workflow involves: Utilizing TypeScript and internal modules to create namespaced classes (internal and pub ...

Unexpected issue encountered during the Angular 9 compilation process

Since migrating to Angular 9, I've encountered an issue with my feature branch after a rebase. Trying to switch to develop and update it using pull origin develop, everything seemed fine until I came across this error that's leaving me puzzled: h ...

Angular: Resetting a conditional form control with matching name

Currently, my code looks something like this: <input *ngIf="a" #autocomplete formControl="myControl"> <input *ngIf="!a" #autocomplete formControl="myControl"> These inputs have different attributes depen ...

Webpack can generate separate compiled files in addition to the bundle

Currently, I am utilizing the webpack loader ts-loader to convert typescript source files into a javascript bundle. My goal now is to not only save the compiled javascript bundle but also the individual compiled javascript files. While I have experience ...

How to Access Data Attribute in React TypeScript on Click Event

Recently, I encountered a situation with my React component where I have a button with a click handler that utilizes the data-* attribute. In the past, with regular React, extracting the value from the data-* attribute was straightforward. However, as I am ...

Having trouble with adding multiple items to an SP list using sp/pnp as I keep encountering an error with the "createBatch()" method

I've been referring to the documentation at to guide me, but I'm encountering an issue with the following code snippet: import { SPFI, spfi, SPFx } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists"; impo ...

What is the proper way to input properties when merging objects for the getInitialState function within a createEntityAdapter object?

How can I use the FetchingStatus type to create a status variable? type FetchingStatus = 'idle' | 'loading' | 'succeeded' | 'failed'; const initialState = companyPagesAdapter.getInitialState({ status: ' ...

Determining the type of nested keyof Properties in Typescript

Looking to create an Array type that contains a chain of nested property names with a specific type requirement. Imagine having the following type: type Foo = { outer: { inner: any; } } Now, I aim to define an Array t ...

Encountering a discord bot malfunction while on my Ubuntu server

My discord bot runs smoothly on my Windows 10 setup, but when deployed to the server running Ubuntu Server 20, it encounters a specific error. The issue arises when trying to handle incoming chat messages from the server. While I can read and respond to m ...

TypeScript requires that the `includes` function must have the same type parameter for both input and

When working with TypeScript, I've encountered an interesting dilemma regarding the use of the Array.Prototype.includes function. It seems that this function requires me to pass in the same type as in the original array, but isn't the purpose of ...

Utilizing Observable Data in Angular 4 TypeScript Components

Looking to extract and assign a JSON value obtained from an API into a variable. Here is an example: TS this.graphicService.getDatas().subscribe(datas => { this.datas = datas; console.log(datas); }); test = this.datas[0].subdimensions[0].entr ...

Upon running the code, no errors appear on the console. However, my project isn't functioning properly and I'm encountering errors on the web console

ReferenceError: require is not defined when trying to access external "url" at Object.url in webpack_require (bootstrap:83) at client:6 importing from webpack-dev-server client index.js(http://0.0.0.0:0) vendor.js:219506 dynamically imp ...

Utilize a general-purpose class for storing static information

My goal is to perform a one-time HTTP request to fetch static data either at application startup or on-demand. I want to store the response in a variable so that I don't have to make multiple requests. Is the approach in my code snippet below the best ...

Verify whether a component is a React.ReactElement<any> instance within a child mapping operation

I am facing a challenge with a component that loops through children and wraps them in a div. I want to exclude certain elements from this process, but I am struggling to determine if the child is a ReactElement or not (React.ReactChild can be a string or ...

Creating a data structure that filters out specific classes when returning an object

Consider the following scenario: class MyClass {} class MyOtherClass { something!: number; } type HasClasses = { foo: MyClass; bar: string; doo: MyClass; coo: {x: string;}; boo: MyOtherClass; }; type RemovedClasses = RemoveClassTypes& ...

Inspecting an unspecified generic parameter for absence yields T & ({} | null)

Recently, I came across a perplexing issue while responding to this specific inquiry. It pertains to a scenario where a generic function's parameter is optional and its type involves the use of generics. Consider the following function structure: func ...