Angular 2 - функция обратного вызова Sweet alert не работает

Я пытаюсь удалить элемент в своем приложении 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» не определен. Он работает правильно, если я не использую сладкое предупреждение в качестве подтверждения. Я предполагаю, что мне нужно передать параметр в функцию обратного вызова, но не знаю, что мне передать. Итак, как я могу это решить?


person parth    schedule 04.10.2017    source источник
comment
Вы можете отправить весь код? Что authService.deleteUser   -  person Manav    schedule 04.10.2017
comment
@manav я обновил код. посмотри   -  person parth    schedule 04.10.2017
comment
может быть, sweetalert перезаписывает this?   -  person Manav    schedule 04.10.2017
comment
Не могли бы вы попробовать лямбда-функцию () => {} вместо function(){}, чтобы сохранить контекст?   -  person Raven    schedule 04.10.2017


Ответы (1)


Первое решение: используйте стрелочная функция, потому что выражение функции связывает 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
            });
        }
    });
person Fetrarij    schedule 05.10.2017