Reputation: 674
I am trying to delete an item in my angular cli app. I've used sweet alert as an alert and i want to delete an item from the list. Here is a code for that. This code is in typescript file.
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
});
});
}
}
Problem is when i confirm delete, it gives me error that "this.authserivce "is undefined. It is working properly if i don't use sweet alert as confirmation. I'm guessing i need to pass parameter in call back function but don't know what should i pass. So how i can solve this?
Upvotes: 0
Views: 4196
Reputation: 7326
1st solution: Use the arrow function because the function expression bind this
with its own 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((result) => {
if (result.value) {
this.authService.deleteUser(userData).subscribe(data => {
// response
});
}
});
2nd solution:
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 => {
// response
});
}
});
Upvotes: 2