如何获得初始确认服务,等待用户的批准或拒绝? [英] How to get the confirmation service of primeng wait for the approval or denial of the user?

查看:43
本文介绍了如何获得初始确认服务,等待用户的批准或拒绝?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使初始确认服务的行为与浏览器本机确认相同?

当用户单击按钮时,我在某些情况下需要请求他们的确认才能继续,如果拒绝,则退出该方法。

以下是使用Primeng确认服务的示例。问题是,调用OpenFile的方法的最后一行是在没有等待用户批准的情况下执行的。

confirm(): void {
  if (this.condition) {
    this.confirmationService.confirm({
      message: 'Are you sure that you want to proceed?',
      header: 'Confirmation',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        this.openFile();
        this.messageService.add({
          severity: 'info',
          summary: 'Confirmed',
          detail: 'You have accepted'
        });

        return;
      },
      reject: () => {
        return;
      }
    });
  }

  this.openFile();
}

另一方面,使用浏览器本机确认实现相同的逻辑。它按预期工作,因此在适当的条件下,它将等待用户的确认

confirm1(): void {
  if (this.condition) {
    const result = confirm('Are you sure that you want to proceed?');

    if (result) {
      this.openFile();

      return;
    } else {
      return;
    }
  }

  this.openFile();
}

openFile方法有一个简单的控制台日志

openFile(): void {
  console.log('Some file');
}

如何获得Primeng的确认服务等待用户的批准或拒绝?

您可以与此存储库中描述的行为示例https://github.com/ilmoralito/sample-primeng-confirmation-service-vs-native-confirmation

进行交互

推荐答案

您可以在Primeng确认服务之上创建一个服务,然后使用Promise作为调用Primeng Confirm服务的自定义确认方法的返回类型,如果接受,则Promise解析为True,如果拒绝,则Promise解析为False。

确认服务

@Injectable({
  providedIn: "root"
})
export class ConfirmService {
  constructor(private confirmationService: ConfirmationService) {}

  confirm({
    message = "Are you sure that you want to proceed?",
    header = "Confirmation",
    icon = "pi pi-exclamation-triangle"
  } = {}): Promise<boolean> {
    return new Promise(resolve => {
      console.log(
        this.confirmationService.confirm({
          message,
          header,
          icon,
          accept: () => {
            resolve(true);
          },
          reject: () => {
            resolve(false);
          }
        })
      );
    });
  }
}

我们可以使用异步/等待,因为确认方法返回承诺

export class AppComponent {
  msgs: Message[] = [];

  constructor(private confirmService: ConfirmService) {}

  async confirm() { 
    if (await this.confirmService.confirm())
      this.msgs = [
        { severity: "info", summary: "Confirmed", detail: "You have accepted" }
      ];
    else {
      this.msgs = [
        { severity: "info", summary: "Rejected", detail: "You have rejected" }
      ];
    }
  }

}


stackblitz demo 🚀

这篇关于如何获得初始确认服务,等待用户的批准或拒绝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆