我正在使用角度,在我的组件中我正在执行以下操作,因为产品可能需要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);
});
}
答案 0 :(得分:1)
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);
});
}