【问题标题】:Angular 2 - Sweet alert call back function not workingAngular 2 - 甜蜜警报回调功能不起作用
【发布时间】:2017-10-04 05:47:17
【问题描述】:

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

【问题讨论】:

  • 你能把整个代码发过来吗?什么是authService.deleteUser
  • @manav 我已经更新了代码。看看
  • 也许 sweetalert 正在覆盖 this?
  • 您可以尝试使用 lambda 函数 () => {} 而不是 function(){} 来保留上下文吗?

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


【解决方案1】:

第一种解决方案:使用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
            });
        }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多