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

时间:2018-08-09 07:26:47

标签: angular

我要进行两个HTTP调用。

下面是我的TypeScript代码

   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完成并重定向到页面,因此会话用户名始终为null。

我尝试使用SetTimeout函数,但是在这里不起作用,是否还有其他方法可以在重定向之前放置延迟,或者有什么方法可以让第一个呼叫等待直到第二个呼叫完成工作?

2 个答案:

答案 0 :(得分:2)

您不必等待GetUserName中的CheckLogin,而只是在调用它而忽略结果。您可以尝试从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. 致电GetUserNamereplace our observable with it
  5. GetUserName返回的观测值完成后,我们可以导航

无需用promise替换RXJS,当您执行异步请求时,它具有强大的功能-特别是在这种情况下,例如当您有多个调用以特定顺序执行时,并且在某些情况下被满足。

答案 1 :(得分:0)

您可以使用Promise

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();
    });
相关问题