Troubleshooting: Issue with callback function in SweetAlert for Angular 2

I'm facing an issue with deleting an item in my Angular CLI app using Sweet Alert as a confirmation dialog. The code snippet below is written in TypeScript:

import { AuthenticationService } from '../../../services/authentication.service';
declare var swal: any;
export class AdminUsersComponent implements OnInit {

    constructor(
        private authService: AuthenticationService,
    ) { }

    deleteUser(id) {
        let userData = {
           user_id: id
        };
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        }, function(){
            this.authService.deleteUser(userData).subscribe(data => {
                // response
            });
        });

    }
}

After confirming the delete action, I encountered an error stating that "this.authserivce" is undefined. The functionality works fine without using Sweet Alert for confirmation. I suspect I need to pass a parameter in the callback function but unsure what it should be. Any insights on how to resolve this issue?

Answer №1

First approach: Utilize the arrow function as it associates the function expression with its own context.

swal({
        title: "Are you sure?",
        text: "You will not be able to recover this!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }).then((result) => {
        if (result.value) {
            this.authService.deleteUser(userData).subscribe(data => {
                // handle response
            });
        }
    });

Second approach:

let that = this;
swal({
        title: "Are you sure?",
        text: "You will not be able to recover this!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        closeOnConfirm: false
    }).then(function(result) {
        if (result.value) {
            that.authService.deleteUser(userData).subscribe(data => {
                // handle response
            });
        }
    });

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

I will not be accessing the function inside the .on("click") event handler

Can someone help me troubleshoot why my code is not entering the on click function as expected? What am I missing here? let allDivsOnTheRightPane = rightPane.contents().find(".x-panel-body-noheader > div"); //adjust height of expanded divs after addi ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

Is it impossible to use type as a generic in TypeScript?

Struggling with TypeScript in React and encountered an issue. I decided to use a generic to build an abstracted class related to Axios. However, I ran into an ESLint error when using any as the type parameter for my generic. ESLint: Unexpected any. Specif ...

Publishing Typescript to NPM without including any JavaScript files

I want to publish my *.ts file on NPM, but it only contains type and interface definitions. There are no exported JavaScript functions or objects. Should I delete the "main": "index.js" entry in package.json and replace it with "main": "dist/types.ts" inst ...

Typescript's puzzling selection of the incorrect overload

I have a method structured as shown below: class Bar { public executeInWorker(cb: () => void): void; public executeInWorker(cb: () => Promise<void>): void | Promise<void>; public executeInWorker(cb: () => void | Promise< ...

When using React MUI Autocomplete, make sure to handle the error that occurs when trying to filter options using the

I am trying to implement an autocomplete search bar that makes a custom call to the backend to search through a list of tickers. <Autocomplete multiple id="checkboxes-tags-demo" options={watchlis ...

What is the process of TypeScript module resolution within the Play framework?

In my Play project, I am interested in incorporating Angular 2 with TypeScript. Utilizing the sbt-typescript plugin and the angular2 WebJAR, I have encountered a situation where Play places the extracted WebJAR in target/web/public/main/lib/angular2. Ideal ...

Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this: export const VALIDATION = { AMOUNT_MAX_VALUE: 100_000_000, AMOUNT_MIN_VALUE: 0, DESCRIPTION_MAX_LENGTH: 50, }; My constant files only contain this one export without any ...

Tips for patiently waiting for a method to be executed

I have encountered a situation where I need to ensure that the result of two methods is awaited before proceeding with the rest of the code execution. I attempted to use the async keyword before the function name and await before the GetNavigationData() me ...

Employ gulp to compile typescript files

While following the angular 2 quick start guide, I noticed that they use a typescript compiler and include a tsconfig.json file. I wanted to find a way to incorporate gulp into this process, and it seems like there are methods available to make it work. Ho ...

Vuejs class-based components using typescript face limitations when it comes to updating data from an external API

Currently, I am utilizing VueJS alongside Typescript and class-based components. In my code, I encountered a warning that states: [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inst ...

Error type not recognized for React-Query mutation.error

While working with a React-Query mutation, I encountered an issue where my component displays an error message but TypeScript does not recognize the mutation.error property as type Error: if (mutation.isError){ console.log(mutation.error.message); ...

Type placeholder for values of objects

For this specific question, the focus is on typings. Imagine we have a basic generic function type: type Fn<T> = (input: T) => boolean The goal is to create a function that, when given an object type as a parameter, will accept an object with th ...

The modifications made to the input type="time" in View do not get updated in the Model within Angular

I have been attempting to validate the input type "time", but I am encountering an issue where changes in the view are not reflected in the model if any of the input fields are left empty. For example: https://i.sstatic.net/1U0sO.png When a user change ...

Scope Error in VueJS Project with TypeScript

I'm facing an issue in my VueJS project with TypeScript where my vue files are divided into HTML, CSS, TS, and vue. The error message I'm getting is: Property '$router' does not exist on type '{ validate(): void; }' Here is ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

How to locate and remove an object in Angular 6

What is the method to remove an object from a list of objects using an id number in Angular 6 with TypeScript? EntityService.ts import { Injectable } from '@angular/core'; import { Entity } from '../../models/entity'; @Injectable({ ...

I recently updated all my projects to Angular 14, but when I tried to install a package using `npm i`, it still

The challenge at hand I encountered an issue with my two Angular projects. The first project serves as a library utilized by the second project. I recently upgraded both projects to Angular 14 following this guide. However, after running an npm i on the ...

Tips on enabling typing support in VS Code and the tsc command for modules that do not use @types?

Currently, I am utilizing the "Rhea" module (https://www.npmjs.com/package/rhea) in my project. This module has its own typings for typescript located in the /typings folder within the module directory (/node_modules/rhea/typings). This differs from the us ...