Angular CanDeactivate Guard无法与Sweet Alert JS一起使用

时间:2019-03-06 00:57:37

标签: angular typescript guard sweetalert sweetalert2

我在Angular中使用Sweet Alert js使用CanDeactivate保护。但确定的点击不会被触发。我是Angular的新手,请协助。这是带有甜蜜警报的代码。显示了“甜蜜警报”,但单击确定不起作用。

export class QuestionEditGuard implements CanDeactivate<FeedbackQuestionEditPage> {
    canDeactivate(component: FeedbackQuestionEditPage): Observable<boolean> | Promise<boolean> | boolean {
        if (component.questionForm.dirty) {
            const question = component.questionForm.get('description').value || 'New Question';
            swal.fire({
                title: 'Hey there!!',
                text: `Navigate away and lose all changes to ${question}?`,
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'OK',
            }).then((result) => {
                return true;
            });

            return false;
        }
        return true;
    }
}

但是使用正常的Confirm,它可以工作。

export class QuestionEditGuard implements CanDeactivate<FeedbackQuestionEditPage> {
    canDeactivate(component: FeedbackQuestionEditPage): Observable<boolean> | Promise<boolean> | boolean {
        if (component.questionForm.dirty) {
            const question = component.questionForm.get('description').value || 'New Question';
            return confirm(`Navigate away and lose all changes to ${question}?`);
        }
        return true;
    }
}

我想念什么吗?

1 个答案:

答案 0 :(得分:3)

您必须像普通的return一样Swal.fire confirm函数

export class QuestionEditGuard implements CanDeactivate<FeedbackQuestionEditPage> {
    canDeactivate(component: FeedbackQuestionEditPage): Observable<boolean> | Promise<boolean> | boolean {
        if (component.questionForm.dirty) {
            const question = component.questionForm.get('description').value || 'New Question';
            return swal.fire({ // <- return here
                title: 'Hey there!!',
                text: `Navigate away and lose all changes to ${question}?`,
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'OK',
            }).then((result) => {
                if (result.value) {  // check if OK pressed
                    return true;
                } else {
                    return false;
                }
            })
        } else {
            return true;
        }
    }
}