如何在 Angular 7 中检查 sweetAlert 上的密码

how to check password on sweetAlert in Angular 7

我一直在尝试检查 sweetAlert 上的用户密码。但是 subscribe 方法一直在最后执行并且效果不佳。有什么可能的方法可以使这项工作吗? 这是我的代码。

swal.fire({
  title: 'Confirm Password',
  input: 'password',
  confirmButtonText: 'Submit',
  focusConfirm: false,
  showLoaderOnConfirm: true,
  preConfirm: (password) => {
    if (password=='') {
      swal.showValidationMessage(`Please enter login and password`)
    }
    else {
      const userName = 'jhonDoe' 
      let a = this.checkPass(userName, password) // excuted 1st
      console.log(a)  // excuted 3rd  ---- which should display if the user password success or not
    }
  }
})


checkPass(userName,password) {
    this.userService.checkPassword(userName, password).subscribe((data: any) => { //excuted 2nd 
      setTimeout(() => {               //excuted 4th
        if (data.succeeded) {
          return data.succeeded
        } else {
          console.log(data.errors[0].description)
          return data.errors[0].code
        }
      }, 500)
    },
    (err: HttpErrorResponse) => {
      return err
    });
  }

您的 userService.checkPassword 是一个异步方法,return 是一个可观察对象。 checkPass 函数没有 return 任何东西,因为 return 都在一些辅助子函数中。

function foo(){
    setIntervall(() => {return 0;}, 0)
}

不会return任何东西。

您需要使用异步策略。最简单的方法是 return Promise:

function checkPass(userName: string, password: string): Promise<boolean> {
  return new Promise<boolean>((resolve, reject) => {
    this.userService.checkPassword(userName, password).subscribe((data: any) => {
          if (data.succeeded) {
              resolve(data.succeeded);
          } else {
              console.log(data.errors[0].description)
              reject(data.errors[0])
          }
      },
          (err: HttpErrorResponse) => {
              reject(err)
          });
  });
}

之后你只需要等待checkPass函数的结果,这不是问题,因为该方法支持异步结果:

preConfirm: async (password) => {
  if (password == '') {
      swal.showValidationMessage(`Please enter login and password`)
  } else {
      const userName = 'jhonDoe'
      let a = await this.checkPass(userName, password) // excuted 1st
      console.log(a)  // excuted 3rd  ---- which should display if the user password success or not
  }
}