Angular 2 - Sweet警报回叫功能不起作用

时间:2017-10-04 05:47:17

标签: typescript angular-cli angular2-services sweetalert sweetalert2

我正在尝试删除我的angular cli应用中的项目。我已经使用甜蜜警报作为警报,我想从列表中删除一个项目。这是一个代码。此代码位于typescript文件中。

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”未定义。如果我不使用甜蜜警报作为确认,它正常工作。我猜我需要在回调函数中传递参数但不知道我应该传递什么。那我怎么解决这个问题呢?

1 个答案:

答案 0 :(得分:2)

第一个解决方案:使用arrow function,因为函数表达式绑定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
            });
        }
    });