我正在尝试实现一个切换按钮,我不知道如何用可观察的方法来处理这个特定的场景。为了防止用户单击和后端的实际响应之间的延迟,我想我可以先使用,,将其更改为新的状态。然后,当后端与更新一起出现时,将后端更新保持为真实的来源。
在dom方面,我使用异步管道。
ButtonComponent侧:
this.isButtonActive$ = this.buttonService.isButtonActive$();DOM侧:
<span *ngIf="isButtonActive$ | async">
...
</span>从服务方面:
public isButtonActive$(): Observable<boolean> {
return this.currentState$.pipe(
map((state) => state.isActive)
);
}只要我从后端获得新数据,它就会监听当前状态$更改并接收新值。
但是,如果后端需要2-3秒的时间来更新,就会产生糟糕的用户体验。
这个想法是,一旦用户单击按钮,它就会立即将其状态更改为新的状态,无论它是否现在失败,后端都会相应地告诉和更新。
如果这是承诺,对我来说很容易解决,但是我如何用可观察的方法来管理这种行为呢?我被迫使用BehaviorSubject吗?
谢谢。
发布于 2021-04-23 17:12:05
我不知道this.currentState$是如何填充的,但是这里我们尝试了一些API调用。
public markActive() {
return this.http.post('myAPIURL', body).pipe(
startWith({
// object you want to set while API call is in progress.
});
);
}https://www.learnrxjs.io/learn-rxjs/operators/combination/startwith
https://stackoverflow.com/questions/67230416
复制相似问题