我如何确保最后一个http帖子在Angular中到达后端
?我的用例。我有一个简单的由我实现的芯片列表。它由芯片和末尾的输入表示。当用户在输入中键入内容并按下Enter
时,带有键入文本的芯片将添加到芯片列表中,用户也可以从列表中删除特定芯片。在添加和删除方面,我正在更新后端的芯片列表。这是负责此的代码段。
addNewChip() {
if(this.chipText) {
this.chips.push(this.chipText);
this.chipText = "";
this.updateChipsOnBE();
}
}
removeChip(chipText) {
this.chips = this.chips.filter(text => text !== chipText);
this.updateChipsOnBE();
}
private updateChipsOnBE(): Observable<string[]> {
return this.chipAPI.update(this.BEAddress, this.chips);
}
现在我担心可能的竞争条件:this.chipAPI.update
操作可能尚未在 BE 上完成,而另一个this.chipAPI.update
操作将以这样的方式触发,即后一个操作将在前一个操作之前完成。这意味着,用户将丢失他或她应用的最后一个更改。
我觉得 RxJS 中应该有一种方法可以防止它,但我既找不到也不能提出解决方案。
您需要在chipAPI
内部使用concatMap
运算符。
像这样:
send$ = new Subject();
constructor(http: HttpClient) {
this.send$.pipe(
// contact waits until the inner stream has been completted.
concatMap(([address, chips]) => this.http.post(address, chips).pipe(
retry(5), // in case of failed request,
// catchError(() => EMPTY), // perhaps we can ignore errors
)),
// takeUntil(this.destroy$), // you need to implement an unsubscribe trigger.
).subscribe();
}
update(address, chips): {
this.send$.next([address, chips]);
}