【发布时间】:2018-08-09 16:44:12
【问题描述】:
我想进行两次 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 完成并在第二次调用完成之前重定向到页面,因此会话用户名始终为空。
我尝试使用 SetTimeout 函数,但它在这里不起作用,有没有其他方法可以在重定向之前设置延迟,或者有任何方法让第一次调用等到第二次调用完成它的工作?
【问题讨论】:
-
我编辑您的问题,因为您没有使用两个 API。
-
this.router.navigate(['/log-tracker']);这必须在GetUserName订阅方法中。 -
使用
switchMap -
@trichetriche,谢谢,但再看一遍,希望你能找到两个 api 的
-
@SujataChanda ,我会尝试这个想法
标签: angular