异步 HTTP 调用,直到在 Angular 中满足条件



我在 Angular 中有一个返回承诺的 HTTP 调用。我正在使用 setTimeout 在间隔后刷新呼叫。是否可以使用一些可以完成这项工作的内置功能/模式?

是的,您可以太轻松地使用 RXJS。但是当然不使用承诺,这就是rxjs的强大功能,如间隔。

interval(1000)
.pipe(
switchMap(() => this.http.get('...url...')),
map(response => {
if(response.statusCode == 1) return response.data;
else return undefined; //or some error message or data.
})
)
.subscribe(response => {
// do somthing with the response that will come in one second interval
});

基本上它看起来像这样。但是,如果您提供自己的代码,我们可以帮助您仅使用 rxjs 完全按照您想要的方式工作。这是建立在非常好的可观察设计模式之上的强大库。