首页 > 解决方案 > 确保最后一个 http 帖子在 Angular 中最后到达后端

问题描述

我如何确保最后一个 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 中应该有一种方法来防止它,但我既找不到也找不到解决方案。

标签: angularrxjsobservablehttpclient

解决方案


您需要concatMapchipAPI.

就像是:

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]);
}

推荐阅读