Encountering an issue when trying to access a class's member variable within the "then" function of

Trying to develop a simple contact list app using Angular 4 and facing an issue with the delete functionality. When attempting to delete a contact, the contacts variable inside the 'then' function is returning undefined.

  1. The main problem lies within the confirmDel() method
  2. The goal is to display an alert asking the user to confirm the deletion of a contact
  3. Once confirmed, the specific contact should be deleted from the component

export class HomeComponent implements OnInit {
  
  contacts: Array<any>;

    // Initializing DataService through dependency injection
    constructor(private _dataService: DataService) {
      this._dataService.getContacts()
          .subscribe(res => { console.log(res);
         this.contacts = res;
         });
          
    }

  ngOnInit() {

    // Sample contact data
    var contact={"firstname":"jishnu","lastname":"koottala","email":"example@email.com","mobile":"7890678970"};

    var appstest = new Array();
    appstest.push({"firstname":"Jishnu","lastname":"Koottala","emailid":"example1@email.com","mobile":"7890678970"});
   
    ...

  }
  

confirmDel(id){
  
 console.log('id is = '+id);
  swal({
    title: 'Are you sure want to delete this contact?',
    text: "You won't be able to revert this!",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes, delete it!'
  }).then(function () {

    var cts = this.contacts;
    
    this.taskService.deleteContact(id).subscribe(data => {
        if(data.n == 1){
            var cts = this.contacts;
            for(var i = 0;i < cts.length;i++){
                if(cts[i]._id == id){
                  cts.splice(i, 1);
                }
            }
        }
    });

    swal(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    );
  })
}


}

Answer №1

Opt for utilizing an arrow function over a standard one to effectively catch 'this' within the declaring context.

Answer №2

swal({ }).then(() =>{ 
//you have permission to view this now
});

Or you can store this in a different variable

const stored=this;
 swal({}).then(function(){
 //You are able to refer back to stored here
 });

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

No data appearing in the console after sending a POST request using Node.js

Is anyone else experiencing issues with retrieving data in the post request below? I'm open to suggestions. var bodyParser = require('body-parser'); var jsonParser = bodyParser.json(); var urlEncodedParser = bodyParser.urlencoded({extende ...

Steps for exporting a package that has been imported

If in file1, the code is like this: import * as Things1 from "../things1" import * as Things2 from "../things2" export { Things1, Things2, } and in file2, it looks like this: import * as Distributor from "../file1" i ...

Unexpected behavior with Angular 10 behavior subject - encountering null value after invoking .next(value) function

Can anyone help me solve the mystery of why my user value turns null after I log in? This is the login page where an API is called and the result is obtained as shown below: https://i.stack.imgur.com/kDjSy.png Here is the authentication service implemen ...

Creating consistent div sizes for varying image and title lengths in bootstrap

In my angular project, I am receiving data in the form of image, title, and location. Despite my efforts to create a responsive div, I have been unsuccessful in achieving uniform sizes. <div *ngFor="let company of companies" class=" ...

Error in Angular 7 Reactive Forms: "No value accessor available for form control without a specified name attribute"

I'm encountering issues with some form fields while using reactive forms in Angular. Any insights on why this might be happening would be greatly appreciated. Just started working with Angular and Material 7, if that's relevant. An interesting ...

Error: passport-local-mongoose does not have a createStrategy or authenticate function

Currently, I am working on enhancing features of a starter project available at this repository. The specific task at hand involves integrating user login functionality using passport-local-mongoose. In my attempts to utilize different strategies for impl ...

The `setState` function is failing to change the current value

I'm having an issue with setting State in the dropdown component of semantic-ui-react while using TypeScript in my code. The selected category value is always returning an empty string "". Any suggestions on how to resolve this problem? impo ...

Invoke a component's function in a different component

Upon clicking the button, I am trying to execute the 'exportHistoryToCSV' method within this component, which in turn calls a method from another component. However, I am encountering an error. @UntilDestroy() @Component({ selector: 'd ...

Having trouble customizing the HTML range input?

I am looking to customize the appearance of a range input slider. Specifically, I want the slider to be green for the lower portion (where the thumb has moved) and grey for the remaining section. I have successfully changed the default styles from blue and ...

Does SharePoint Online support the .webmanifest format? What is the process for creating a Progressive Web Application in SharePoint Online using a supported webmanifest file?

Currently, I am in the process of developing a Progressive Web Application for SharePoint Online by utilizing the Angular 8 PWA build. The service worker and application are running smoothly; however, I have encountered an issue with loading the webmanifes ...

Issue with Angular 8: Unable to access property 'database' of undefined when using @firebase

Recently, I decided to upgrade my configuration from angularfire2 v4 to @angular/fire v5.2.1 and firebase from v4 to v6.2.4. Unfortunately, during this process, I encountered an issue that caused the console to log the following error message: TypeError: ...

Utilizing an external library in a Typescript 2.0 project: A comprehensive guide

I am currently working on a Typescript 2.0 project that utilizes Common JS modules and System JS loader. My IDE of choice is Visual Studio code. I am encountering a challenge with integrating an external library (filesaver JS) into my project. After insta ...

Retain the parameter name when defining a function type mapping

Imagine you need to change the result of a function: (bob: Bob) => R => (bob: Bob) => R2 Is it possible to achieve this without changing the argument name? (e.g bob instead of using a general name like a) ...

Having difficulty setting custom icons for clustering in Google Maps MarkerClusterer due to the absence of position data

I am struggling to understand the documentation for this utility. It seems that to customize cluster icons, I need to convert the cluster icon to a marker using the MarkerClusterer's renderer property and then apply icon styles as if it were a normal ...

Customizing the appearance of all Angular components with styles.scss

Is there a way to create a universal style in styles.scss that can be applied to all Component selectors (e.g. app-componentA, app-componentB ...)? I understand that I could manually add the style to each selector, but I am concerned that it may be forgot ...

Establishing the initial state within the constructor of a React Component utilizing a generic state

I have encountered an issue with React and Typescript. I am working on a component that utilizes two generics for props and state. interface Props { foo: string; } interface State { bar: string; } class Foo< P extends Props = Props, S e ...

Utilize CSS Styles with Angular 2 Component Selectors

I'm currently diving into Angular 2 and I've been pondering the idea of implementing CSS styles using the component selector in this manner: the component @Component({ selector: 'app', styleUrl: './local.css', te ...

Watchable: Yield the outcome of a Promise as long as watching continues

I am looking to create a function in Angular and TypeScript that will return an Observable for subscription. This Observable should emit the result of a Promise every three seconds. Currently, I have a function that returns a Promise, but I need it to ret ...

Guide on Implementing a Function Post-Rendering in Angular 2+

I'm looking to implement some changes in the Service file without modifying the Component.ts or directive file. Here's what I need: 1) I want to add an event listener after the service renders its content (which is generated by a third-party tool ...

Follow the correct sequence when tapping the pipes and disregard the outcomes

I'm having trouble with executing tap functions in observables. In my scenario, I have a series of API requests that are dependent on each other. To handle this, I store the necessary data for the next request in class properties and use tap function ...