我遇到了一些奇怪的问题,我有 2 个 http axios 调用, 调用 1:POST:此调用返回 stateId 调用 2:GET:此调用使用 stateId 并返回该特定州的城市
const cities = this.httpService.post('https://getAlldata/getStates', body, headers)
.pipe(
switchMap((stateResponse: AxiosResponse<any>) => {
const headers2 = {
headers: { Authorization: `Bearer ${token}` }
params: { stateID: stateResponse.data.stateId } // first POST response stateId is used here
}
console.log(response.data.stateId) //stateId is getting printed on console
return this.httpService.get(URL, headers2);
}),
map((resp2: AxiosResponse<any>) => {
return resp2.data
}),
)
在上面的代码中,我收到错误提示
stateID not passed
,这看起来像是竞争条件问题,在获取 stateID 之前执行调用 2
如果我只是像下面这样在参数中传递硬编码的 stateId:
params: { stateID: 23 }
我能够从呼叫 2 获得响应,即获取 Http 请求
另一件事是,如果我只是设置 3 秒的超时时间,那么我将在不传递硬编码值的情况下从调用 2 获得响应。
另一个谜是,如果我只是执行 console.log() 然后值打印在控制台上
我在堆栈溢出上搜索了很多,但没有找到等待调用 1 解析该值的方法,我想在不添加超时或延迟的情况下实现这一点。
不使用超时,应该有某种机制来等待 Http Call 1 给我们结果。
我尝试使用
mergeMap
和concatMap
来解决这个问题,但它没有帮助。
还有
tried to convert observable to Promise
并使用链式 .then()
但它仍然没有帮助。
我试过
firstValueFrom
和lastValueFrom
但不是运气
也尝试过
Async/await
但没有帮助