每 5 秒订阅一次可观察量,并在 Angular 中满足条件时停止



我正在使用角度,在我的组件中我正在执行以下操作,因为产品可能需要长达 5 秒才能插入后端

this.productService.insert(this.product).subscribe(res => {
setTimeout(() => {
this.refreshList();
this.res = res;
this.enableButton = true;
}, 5000);
}, err => {
});

无论如何我可以改进此代码吗?我看到一堆使用Observable.interval和takeWhile的帖子。使用上述解决方案,如果不满足条件,我无法使其重复,如果满足条件,则停止。

以下是我正在尝试做的更新版本:

public myFunction(): void {
this.disableButton = true;
this.productService.insert(this.product)
.switchMap(_ => Observable.timer(5000)
.do(this.refreshList)).takeWhile(() => this.productList.length === 0).subscribe(res => {
this.result = res;
this.disableButton = false;
}, err => {
// handle error messages
console.log(err);
});
}

Observable.timer 应该做你想做的事。

this.productService.insert(this.product)
.switchMap(res =>Observable.timer(5000).do(this.refreshList))
.takeWhile(()=>your condition...).subscribe()

编辑:做:

public myFunction(): void {
this.disableButton = true;
this.productService.insert(this.product)
.switchMap(_ => Observable.timer(5000)
.do(this.refreshList),(res=>res)).takeWhile(() => this.productList.length === 0).subscribe(res => {
this.result = res;
this.disableButton = false;
}, err => {
// handle error messages
console.log(err);
});
}

相关内容