【问题标题】:How to wait for HTTP Request Response + Confirm Dialogue PopUp + Angular 8如何等待 HTTP 请求响应 + 确认对话框弹出 + Angular 8
【发布时间】:2020-04-16 10:40:29
【问题描述】:

我有一个要求,我想在重定向到其他页面之前显示确认弹出消息,在那里我从用户天气中获取输入,他想要离开未保存的更改。

发生了什么!

在浏览器确认对话框首先出现然后得到不正确的 HTTP-Request 响应。

应该是什么!

我希望首先获得 HTTP 响应,如果满足条件,则弹出确认对话消息。

这是我用于我的项目的代码示例。

service.ts 文件

 async IsUnSavedRosterExistsTwo() {
    console.log('async method called');
    const url = this.util.getBaseURL() + apiURLs.IsUnSavedRosterExists;
    const rr =  await this.http.get<boolean>(url).toPromise();
    console.log(rr);
    return rr;
  }

我已经尝试了所有可能的解决方案,例如 subscribe、promise、pipe,但这里没有任何效果。

component.ts

canDeactivate() {
    this.saveDownloadButton = false;
    // const IsUnSavedRosterExists = this.rosterService.IsUnSavedRosterExists();
    const IsUnSavedRosterExists = this.rosterService.IsUnSavedRosterExistsTwo();

    debugger;
    if (IsUnSavedRosterExists) {
      console.log('executing the code');
      return confirm('You have unsaved Employee Data. Do you wish to proceed without saving?');
    } else {
      this.saveDownloadButton = false;
    }
    return this.saveDownloadButton;
  }

简而言之,我想先等待http-request响应,然后执行if条件满足然后弹出确认对话框,否则重定向到其他页面。

如果我的问题不清楚,请告诉我。

【问题讨论】:

  • IsUnSavedRosterExistsTwo 没有返回任何内容?它不应该返回rr

标签: angular async-await httprequest angular8


【解决方案1】:

您必须将 canDeactivate() 函数转换为 async 函数,然后才能为 this.rosterService await .IsUnSavedRosterExistsTwo() 函数在继续之前解决。请看下面的代码:

async canDeactivate() {
    this.saveDownloadButton = false;
    const IsUnSavedRosterExists = await this.rosterService.IsUnSavedRosterExistsTwo();

    debugger;
    if (IsUnSavedRosterExists) {
      console.log('executing the code');
      return confirm('You have unsaved Employee Data. Do you wish to proceed without saving?');
    } else {
      this.saveDownloadButton = false;
    }
    return this.saveDownloadButton;
  }

【讨论】:

  • 对于即将面临同样问题的开发人员..确保您已将您的 canDeactive 方法设置为异步方法,而不是调用您的服务方法的任何内部方法....
猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2018-06-03
  • 1970-01-01
  • 2018-11-13
相关资源
最近更新 更多