如何等待HTTP请求响应+确认对话框弹出+ Angular 8

时间:2019-12-26 05:23:44

标签: angular async-await httprequest angular8

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

发生了什么事!

在浏览器上,首先出现确认对话框,然后获取不正确的HTTP请求响应。

应该是什么!

我希望首先获得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;
  }

我已经尝试了所有可能的解决方案,例如订阅,promise,管道,但这里什么都没做。

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请求响应首先出现,然后在条件满足时执行,然后弹出确认对话框,否则重定向到其他页面。

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

1 个答案:

答案 0 :(得分:1)

您必须将 canDeactivate()函数转换为 async 函数,然后可以 await 来获取 this.rosterService .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;
  }