0

我正在尝试删除我的 Angular cli 应用程序中的一个项目。我使用了甜蜜警报作为警报,我想从列表中删除一个项目。这是一个代码。此代码在打字稿文件中。

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
            });
        });

    }
}

问题是当我确认删除时,它给了我“this.authserivce”未定义的错误。如果我不使用甜蜜警报作为确认,它会正常工作。我猜我需要在回调函数中传递参数,但不知道我应该传递什么。那么我该如何解决呢?

4

1 回答 1

2

第一种解决方案:使用箭头函数,因为函数表达式this与其自己绑定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
            });
        }
    });

第二种解决方案:

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
            });
        }
    });
于 2017-10-05T09:37:44.300 回答