Confirmation in Sweet Alert before deleting an item in Angular 2

Currently, I am facing an issue with my AlertService that uses Sweet Alert. My goal is to confirm whether the user truly wants to delete something before proceeding with the action. Despite utilizing arrow functions and attempting bind(), I am encountering difficulties with callbacks context switching. Below is the code snippet:

AlertService

/**
 * This function presents a generic confirmation alert.
 * @param object containing properties to display
 * @return {boolean} true if confirmed, otherwise null
 * 
 * For example, pass 'warning' in the type attribute to generate a warning alert.
 */
confirmAlert(object: any, callback: Function): any {
    swal({
        title: object.title,
        text: object.text,
        type: object.type,
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'OK'
    }).then(function (res) {
        swal({
            title: object.confirmTitle,
            text: object.confirmText,
            type: 'success'
        });
        return callback(true);
    }, function (cancel) {
        swal({
            title: 'Cancelled',
            text: 'Action cancelled',
            type: 'error'
        })
        return callback(null);
    });
}

UsersComponent

/**
 * Removes the selected user after confirming with an alert.
 * Updates the current users array displayed in a table.
 */
deleteUser() {
    let usersToDelete = {
        'users': this.users
    };
    this.alertService.confirmAlert(this.createMessages.alert.delete, (confirm) => {
        if (confirm) {
            this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => {
                if (res.status == 200) {
                    this.alertService.okAlert(this.createMessages.alert.deleteSuccess);
                }
            });
        }
    });
    this.refreshUsers();
}

The issue lies in the fact that the object containing the selected users does not reach the webService. Upon examining all logs, I identified this as the root cause of the problem, but I am unsure how to address it.

Answer №1

The issue stemmed from having the refreshUsers() function placed outside of the callback, unknowingly causing it to clear out my this.users array:

/**
 * Removes the selected user after confirming with an alert and refreshing the user list.
 */
deleteUser() {
    let usersToDelete = {
        'users': this.users
    };
    this.alertService.confirmAlert(this.allMessages.alert.delete, (res) => {
        if (res) {
            this.webService.delete(environment.routes.users.userUrl, usersToDelete).subscribe(res => {
                if (res.status == 200) {
                    this.refreshUsers();
                }
            });
        }
    });
}

/**
 * Responsible for updating the displayed user table by removing a selected user and refreshing the list.
 * Identifies the user and its index.
 * Deletes from the all array and the users array.
 * Triggers a refresh by calling getAllUsers().
 */
refreshUsers() {
    while (this.users.length > 0) {
        this.all.forEach(element => {
            let i = this.users.indexOf(element._id);
            if (i != -1 && this.users.length >= 0) {
                let e = this.all.indexOf(element);
                this.all.splice(e, 1);
                this.users.splice(i, 1);
                this.getAllUsers();
            }
        });
    }
}

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

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

Creating custom Moment.js plugins within an Ionic 2/Cordova project using TypeScript

In my Typescript Ionic 2 project, I am utilizing the moment.js library. To include it in my project, I use the following code snippet: import * as moment from 'moment'; Once imported, I can use moment in my component like so: let endDate = mom ...

Is it feasible to arrange tables in ng-bootstrap Sortable Tables by default column selection?

Currently, I am in the process of developing an Angular project that utilizes the ng-bootstrap Sortable Table component. This particular component can be found at the following link: My issue lies in the fact that I require the table to automatically sort ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

Angular is having trouble properly rendering the Array Description

I'm currently working on a project using .net core MVC with an Angular frontend. I am facing an issue where the description of parameter arrays is not displayed in the output, even though single parameters display correctly. How can I resolve this pro ...

Tips for merging individual Koa-Routers using Typescript

My approach to organizing routers in my project involved categorizing them based on their purpose. Here's how they are structured: routers/homeRouter.ts import * as Router from 'koa-router'; const router: Router = new Router(); router ...

Can a generic type be utilized to instantiate an object?

In my code, I have a class named Entity as shown below: class Entity { constructor(readonly someValue: string) {} someFunction() {} } Now, I am trying to create a class that will handle these entities and be able to create instances of them. In or ...

Guide to implementing asynchronous REST API requests in Ionic 2

I'm working on an app for a school that allows students to scan their ID cards and enter. On the teacher's side of the application, I display the number of students present in each class. Currently, I am using a refresher to reload the page and u ...

A Guide to Testing Directives in Angular 2: Unit Testing Tips

Issue: My goal is to perform unit testing on an Angular 2 directive to ensure proper compilation. In the context of Angular 1, one could utilize the$compile(angular.element(myElement) service followed by calling $scope.$digest(). I am specifically looking ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...

Error encountered while loading a plugin in Typescript and RequireJS compilation process

Currently, I am working on a Typescript application in Visual Studio 2015 where RequireJS is used for loading modules. I have successfully loaded various modules from .ts classes and external libraries by using their typing .d.ts files. However, I have en ...

What is the process for running an older Angular project using ng serve?

I'm currently attempting to run a sample Angular project that is part of a third-party framework by using the command ng serve. It seems like this sample project requires Angular version ~4 based on the information in its package.json file. My global ...

Encountering an error with the Typescript 'any' type in Ionic 2

I need help understanding an error I encountered: EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in build/pages/search/search.html:17:14 ORIGINAL EXCEPTION: Cannot find a differ supporting object 'function () { return [ { ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

Utilizing SVG Images on Buttons within Material Design (MD-Icon)

I have experimented with different methods, but none seem to be effective: <button md-icon-button color="primary"> <md-icon md-svg-src="./assets/img/sprites.svg">menu</md-icon> </button> and also tried this: <md-icon svgSrc= ...

The Angular 5 post request is triggering duplicate responses

Once I log in, the authService is triggered and the routing directs me to the profile component. However, I've noticed that the post request is somehow being sent twice, even though I'm not using Cors. Could it be related to a preflighted reques ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

connect validation of the form to a separate component from the current one

Currently, I am working on creating a searchable-dropdown component that I intend to use in multiple components. However, I am facing an issue with binding form validation to this component. For instance, I have a form for creating a user and I need to bi ...

Automatically adjusting column heights

I'm currently dynamically creating a group of columns, as demonstrated below: <div *ngFor="let col of colList"> <corp-column [xs]="'12'" [sm]="'6'"> <div class="tile tile-default"> <div cla ...

Angular 7: Show selected value upon clicking Radio button

I am having an issue with a radio button where I need to display a value when it is clicked. For example, when the "weekly" option is selected, I want it to display "Weekly" in the "Selection" element. I have tried to implement this but it is not working a ...