等待多个 HTTP 调用结束,然后再执行某些操作



我想进行两次HTTP调用。

下面是我的打字稿代码

   CheckLogIn() {
    this.http.get<boolean>(this.baseUrl + 'api/LogIn/CheckLogIn/' + this.StaffCode).subscribe(result => {
      setTimeout(() => {
        if (result == true) {
          this.GetUserName();
          sessionStorage.setItem("UserID", this.StaffCode);
          this.router.navigate(['/log-tracker']);
        }
      }, 5000)
    }, error => console.log(error));
  }
 GetUserName() {
    this.http.get(this.baseUrl + 'api/Common/GetUserName/' + sessionStorage.getItem("UserID"), { responseType: 'text' }).subscribe(result => {
      console.log(result);
      sessionStorage.setItem("UserName", result);
    }, error => console.log(error));
  }

在CheckLogin((中,我正在调用一个端点,在此调用的响应中,我正在调用另一个端点(GetUserName(,然后重定向到另一个页面。

但是checkLogin不会等待GetUserName完成并重定向到页面,然后第二次调用完成其工作,因此会话用户名始终为空。

我尝试使用 SetTimeout 函数,但它在这里不起作用,有没有其他方法可以在重定向之前设置延迟,或者有任何方法可以让第一次调用等到第二次调用完成其工作?

你不是在等待GetUserNameCheckLogin你只是在调用它并忽略结果。您可以尝试从GetUserName返回可观察量 - 这里也是一个很好的机会来使用其他 RXJS 运算符。

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/do';
CheckLogIn() {
  this.http.get<boolean>(this.baseUrl + 'api/LogIn/CheckLogIn/' + this.StaffCode)
    .filter(result => result)
    .do(() => sessionStorage.setItem("UserID", this.StaffCode))
    .mergeMap(() => this.GetUserName())
    .subscribe( // This does not execute until the observable from GetUserName is complete
       result => this.router.navigate(['/log-tracker']),
       error => console.log(error)
    );
}
GetUserName() { // I now return an observable
  return this.http.get(this.baseUrl + 'api/Common/GetUserName/' + sessionStorage.getItem("UserID"), { responseType: 'text' })
    .do(result => sessionStorage.setItem("UserName", result));
}

现在我们执行以下操作:

  1. 呼叫CheckLogin
  2. 如果结果为真,请继续
  3. 在会话存储中设置UserID
  4. 调用GetUserName并用它替换我们的可观察量
  5. GetUserName返回的可观察量完成时,我们可以导航

没有必要用 promise 替换 RXJS,当你执行异步请求时,它有很大的功能——在这种情况下,当你有多个调用要按特定顺序执行时,它尤其出色,并且必须满足的条件。

你可以使用承诺

CheckLogIn() {
  try {
    return new Promise((resolve, reject) => {
      this.http.get<boolean>(this.baseUrl + 'api/LogIn/CheckLogIn/' + this.StaffCode).subscribe(result => {
        setTimeout(() => {
          if (result == true) {
            this.GetUserName();
            sessionStorage.setItem("UserID", this.StaffCode);
            this.router.navigate(['/log-tracker']);
          }
        }, 5000)
      }, error => console.log(error));
      resolve();
    })
  } catch (error) {
    console.log(error);
  }
}

像这样调用你的 Checklogin 函数

this.CheckLogIn().then(()=>{
      this. GetUserName();
    });

最新更新