我有 2 个调用一些 API 的方法:
getData(param)
。getAnotherData(分别从获取数据)
。
下面的方法调用第一个方法:
this.service.getData(param).subscribe(res => {
this.variable = res;
// here based on the first response i will call the second api
this.service.getAnotherData(this.variable['data']).subscribe(res2 =>
// Here, I will get a response which will be either "started"
// or not "started". If it's not "started", then I have to call
// this API until I get "started" for up to 1 minute.
)})
我怎样才能实现这个目标?
最佳答案
尽量避免嵌套订阅。相反,请尝试使用更高阶的映射运算符,例如
switchMap
。您可以使用 RxJS
repeat
和takeWhile
运算符再次订阅可观察对象,直到它满足条件。
尝试以下操作
this.service.getData(param).pipe(
switchMap(res =>
this.service.getAnotherData(res['data']).pipe(
repeat(),
takeWhile(res => res === 'started') // poll `getAnotherData()` until response is 'started'
)
)
).subscribe(
res => { },
err => { }
);
关于javascript - 在满足条件之前无法使用计时器调用嵌套函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916159/