-2

I am trying to develop a simple contact list app using angular4 I want to delete the contact after click of confirm button,on delete method, it is giving undefined for contacts inside then function.

  1. The problem is on confirmDel() method
  2. My intention is to give an alert on the method, want to delete it or not
  3. after confirmation I want to delete that particular component My homeComponent code is as follows:

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

    // Create an instance of the DataService through dependency injection
    constructor(private _dataService: DataService) {
      
     
      // Access the Data Service's getUsers() method we defined
      this._dataService.getContacts()
          .subscribe(res => {console.log(res);
         this.contacts=res;
         });
          
    }

  ngOnInit() {


    var contact={"firstname":"jishnu","lastname":"koottala","email":"jishnu45@gmail.com","mobile":"7890678970"};

var appstest = new Array();
    appstest.push({"firstname":"Jishnu","lastname":"koottala","emailid":"jishnu45@gmail.com","mobile":"7890678970"});
    appstest.push({"firstname":"Luvish","lastname":"yadav","emailid":"luvishyadav@gmail.com","mobile":"787447970"});
    appstest.push({"firstname":"Mohan","lastname":"singh","emailid":"mohan.singh3@gmail.com","mobile":"78906576770"});
    appstest.push({"firstname":"Anurag","lastname":"dwivedi","emailid":"anurag.dwivedi@gmail.com","mobile":"78975778970"});

  //  this.contacts=appstest;
  }
  

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 () {
    //this._dataService.deleteContact(id);



    var cts = this.contacts;
    
    this.taskService.deleteContact(id).subscribe(data => {
        if(data.n == 1){
    var cts = this.contacts; //i have to use 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'
    );
  })
}


}

2 Answers2

1

You should use an arrow function instead of a regular function in order to capture this from the declaring context.

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

swal({ }).then(() =>{ //you can access this here });

Else preserve this within other variable

const self=this; swal({}).then(function(){ //You can access self here });

Kay
  • 1,266
  • 10
  • 21